【发布时间】:2019-06-07 11:57:21
【问题描述】:
我有几个不同的接口和对象,每个都有type 属性。假设这些是存储在 NoSQL 数据库中的对象。如何根据输入参数type 创建具有确定性返回类型的通用getItem 函数?
interface Circle {
type: "circle";
radius: number;
}
interface Square {
type: "square";
length: number;
}
const shapes: (Circle | Square)[] = [
{ type: "circle", radius: 1 },
{ type: "circle", radius: 2 },
{ type: "square", length: 10 }];
function getItems(type: "circle" | "square") {
return shapes.filter(s => s.type == type);
// Think of this as items coming from a database
// I'd like the return type of this function to be
// deterministic based on the `type` value provided as a parameter.
}
const circles = getItems("circle");
for (const circle of circles) {
console.log(circle.radius);
^^^^^^
}
类型“圆|”上不存在属性“半径”方”。
【问题讨论】:
标签: typescript