我试图了解 typescript 在这里是如何工作的。对于具有相似对象属性的对象,我能够处理。但像这样的事情怎么样?
形状具有不同的对象值。如何运行这个函数而不出错?
type Shape =
| { kind: "circle"; radius: number }
| { data: "square"; x: number };
function area(s: Shape) {
if (s.kind === "circle") {
return Math.PI * s.radius * s.radius;
} else {
return s.x * s.x;
}
}
PS:这是一个损坏的代码。
最佳答案
圆形和方形都需要有 kind
属性。
下面应该可以工作。
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; x: number };
function area(s: Shape) {
if (s.kind === "circle") {
return Math.PI * s.radius * s.radius;
} else {
return s.x * s.x;
}
}
关于typescript - 如何处理 typescript 中的不同类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72641121/