我有这样的数据结构:
const VALUES = {
val1: {...},
val2: {...},
val3: {...}
};
const DATA = [
{
name: "name1",
value: "val1" // The value here, is a KEY (not a value) in the "VALUES" object.
},
{
name: "name2",
value: "val2"
}
];
type DataType = typeof DATA[number];/*{
name: string;
value: string; // I want this to be inferred as "typeof keyof VALUES"
}*/
所以我的问题是;有没有办法提示TypeScript value
中的type DataType
应该具有类型typeof keyof VALUES
(而不是string
)而不必显式创建类型?可能是这样的:
const DATA = [
{
name: "name1",
value: (keyof VALUES).val1
},
{
name: "name2",
value: (keyof VALUES).val2
}
];
答案 0 :(得分:1)
您可以使用type assertion:
const DATA = [{ name: "name1", value: "val1" as keyof typeof VALUES }];
但是我宁愿定义一个类型并将其显式用于DATA
变量。这样,打字稿将验证值确实是有效的键。