我有一个对象,例如:
const CATEGORIES = {
diet: {
id: 'diet',
title: 'Diet',
...
},
...
}
如何为它编写类型,以便TypeScript确保嵌套的id
属性与父对象中对象的键匹配?
我尝试过...
const CATEGORIES: {
[T in string]: {
id: T
title: string
}
} = { ... }
...但是这似乎仍然接受id
的任何字符串。
我假设它以某种方式使用了映射的类型和泛型,但是即使有可能,我也不太清楚语法是什么。
答案 0 :(得分:1)
您无法映射所有string
并使其按照您想要的方式运行;参见microsoft/TypeScript#22509。您将需要一组string literal键来进行映射。实现此目的的一种方法是使用通用帮助函数,该函数从传入的值中推断那些键,并验证每个属性的id
子属性是否与其键相匹配:
const asCategories = <T extends { [K in keyof T]: { id: K, title: string } }>(t: T) => t;
您可以测试一下它是否对良好的价值感到满意:
const CATEGORIES = asCategories({
diet: {
id: 'diet',
title: 'Diet',
//...
},
//...
}); // okay
并对坏人生气:
const BADCATEGORIES = asCategories({
diet: { id: "diet", title: "Diet" },
exercise: { id: "exersice", title: "Exercise" } // error!
// -------> ~~
// Type '"exersice"' is not assignable to type '"exercise"'.
})
好的,希望能有所帮助;祝你好运!