[Typescript] Exhaustive conditionals – UnreachableError helper class


class UnreachableError extends Error {
  constructor(_nvr: never, message: string) {
    super(message)
  }
}

class Car {
  drive() {
    console.log("vroom")
  }
}
class Truck {
  tow() {
    console.log("dragging something")
  }
}
class Boat {
  isFloating() {
    return true
  }
}
type Vehicle = Truck | Car | Boat
 
let myVehicle: Vehicle = obtainRandomVehicle()
 
// The exhaustive conditional
if (myVehicle instanceof Truck) {
  myVehicle.tow() // Truck
} else if (myVehicle instanceof Car) {
  myVehicle.drive() // Car
} else {
  // NEITHER! 
  // Argument of type 'Boat' is not assignable to parameter of type 'never'
  throw new UnreachableError(myVehicle, `There is a unreacheable code for ${myVehicle}`)
}

 

原创文章,作者:bd101bd101,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/278575.html

(0)
上一篇 2022年8月3日 07:05
下一篇 2022年8月3日 07:05

相关推荐

发表回复

登录后才能评论