我有一个对象,它的对象如下:
const CATEGORIES = {
diet: {
id: 'diet',
title: 'Diet',
...
},
...
}我如何为它编写一个类型,这样TypeScript才能确保嵌套的id属性与父对象中的键匹配?
我试过..。
const CATEGORIES: {
[T in string]: {
id: T
title: string
}
} = { ... }...but这似乎仍然接受id的任何字符串。
我假设它以某种方式使用了映射类型和泛型,但我不太清楚它的语法是什么,如果可能的话。
发布于 2020-06-26 10:56:45
您不能在这里映射整个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"'.
})好的,希望这会有帮助;祝你好运!
https://stackoverflow.com/questions/62587226
复制相似问题