【发布时间】:2023-02-02 19:52:27
【问题描述】:
我有这样的功能
interface Cat {
color: string,
weight: number,
cute: Boolean, // eventhough all cats are cute!
}
export const doSomething = (
cat: Array<Cat| null>,
index: number,
key: keyof typeof cat,
payload: string | number | Boolean
) => {
....
cat[key] = payload
....
}
这给了我
元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型
我的理解是因为 TypeScript 认为
key可以是任何字符串而不是"color", "weight", "cute"之一。 我如何在函数声明中说明key是三个 ("color", "weight", "cute") 之一?我试过了
... key: keyof Cat, ...没有运气。这个
cat[key] = payload现在给我
输入“字符串|编号 |布尔值 | ' 不可分配给类型 '(string & number & Boolean )
【问题讨论】:
-
但是
cat是Cat元素的数组。所以就是钥匙是数组索引,因此是整数。 -
@GabrielePetrioli 我知道。有没有办法告诉 TypeScript 传递给
key的string必须是Cat中定义的keys("color", "weight", "cute") 之一?
标签: typescript