【发布时间】:2021-12-17 01:56:34
【问题描述】:
我有两个接口。
interface Person {
name: string;
weight: number;
}
interface Dog {
name: string;
mass: number
}
const attribute = isDog ? 'mass' : 'weight';
const player: Person | Dog = "Object with specific type"
if (player[attribute] === 0) return;
我有这个错误:
TS7053:元素隐式具有“任何”类型,因为表达式类型为“质量”| "weight"' 不能用于索引类型 'Person |狗'。
API 可以返回 Dog 或 Person,这取决于其他参数。我想知道告诉 TS 如果玩家是人使用“重量”,如果玩家是狗使用“质量”的最佳方式是什么。我不想使用“任何”类型。
【问题讨论】:
-
好吧,TypeScript 试图在这里提供帮助。如果
attribute是"mass",但player是Person,那么这将是一个合法错误,因为Person.mass不存在 -
您不必从外部做出这种区分。
Person和Dog都应该以同样的方式暴露它们的质量(extends Massive?),所以这不会传播到你的整个代码库。
标签: typescript types computed-properties