C/C++教程

[Typescript] Exhaustive conditionals - UnreachableError helper class

本文主要是介绍[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}`)
}

 

这篇关于[Typescript] Exhaustive conditionals - UnreachableError helper class的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!