我使用的是typescript,有一个用不同人名定义的对象:
const data = {
John: someTypedVariable,
Alex: someTypedVariable,
Anna: someTypedVariable,
... hundreds more added over time
}
如果我尝试访问
data.missingValue
它将正确地无法编译。
如果我尝试迭代对象:
for(const key in data){
const item = data[key]; // error
}
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ John: ....
我可以改变
data
致:
const data: Record<string, someTypedVariable> = {
...
}
但这样我就失去了打字功能,这会导致像这样的错误
数据丢失值
.
那么,有没有一种方法可以在不明确定义密钥列表的情况下保证有效属性,比如:
type keys = "John" | "Alex" | "Anna" | ...hundreds more