我有一条switch
语句,涵盖了所有编译时间的可能性,但是,由于该值可以由用户提供,因此我希望在运行时处理意外的值。
这似乎是打字稿的类型推断太好的地方,它分配类型never
(因为从编译器的角度来看,这永远不会发生),并且不会让我访问它的任何字段。
type Circle = { shape: "circle", radius: number };
type Rectangle = { shape: "rectangle", length: number, width: number };
function area(shape: Circle | Rectangle): number {
switch (shape.shape) {
case "circle": return Math.PI * shape.radius * shape.radius;
case "rectangle": return shape.length * shape.width;
}
throw new Error(`Unexpected shape '${shape.shape}'`); // Error: Property 'shape' does not exist on type 'never'.
}
是否有一种优雅的方法来修复最后一行? (比强制转换为any
或使用下标运算符更为优雅)。
答案 0 :(得分:1)
此页面提供了一个解决方案: https://www.typescriptlang.org/docs/handbook/advanced-types.html
适合您的示例:
type Circle = { shape: "circle", radius: number };
type Rectangle = { shape: "rectangle", length: number, width: number };
function throwOnNever(x: {shape: string}): never {
throw new Error(`Unexpected shape: ${x.shape}`);
}
function area(shape: Circle | Rectangle): number {
switch (shape.shape) {
case "circle": return Math.PI * shape.radius * shape.radius;
case "rectangle": return shape.length * shape.width;
default: return throwOnNever(shape);
}
}