• 欢迎光临~

[Typescript] Exhaustive conditionals - UnreachableError helper class

开发技术 开发技术 2022-08-02 次浏览
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}`)
}

 

程序员灯塔
转载请注明原文链接:[Typescript] Exhaustive conditionals - UnreachableError helper class
喜欢 (0)