我知道这个问题可能已经在其他地方得到了答案,但如果不是,有人能帮我得到嵌套对象的类型吗?我们讨论的是一个有多个其他对象的对象,但是它们看起来几乎是一样的。
const VALUES = {
currentStreak: {
display: "Current streak",
value: currentStreak,
},
longestStreak: {
display: "Longest streak",
value: longestStreak,
},
contributionsThisYear: {
display: "Contributions this year",
value: contributionsThisYear,
},
totalContributions: {
display: "Total contributions",
value: totalContributions,
},
currentCompany: {
display: "Working at",
value: currentCompany,
},
}这就是目标,这就是我所拥有的。它对主键运行良好,但我也希望键入每个对象的键。
export type Something = {
[key in keyof typeof VALUES]: { [key: string]: string | number };
};我怎样才能把第二部分弄对?因此,每个对象都有display和value,value是数字或字符串。
抱歉,如果这是重复!我希望能一劳永逸地理解这一点。
发布于 2022-04-17 19:10:37
如果Something应该是VALUES的类型,那么您就会遇到问题,因为您正在引用要在其自己的类型声明中键入的对象。
除非您有某种具有字符串值的Enum来提取键,否则您应该键入键作为string:
interface innerSomething {
display: string
value: number | string
}
type Something = {
[key in string]: innerSomething
}对于Enum,应该是这样的:
enum SomethingKeys {
currentStreak,
longestStreak,
contributionsThisYear,
totalContributions,
currentCompany
}
interface innerSomething {
display: string
value: number | string
}
type Something = {
[key in keyof typeof SomethingKeys]: innerSomething;
}您也不能在实际的Something声明中声明接口和声明内部对象的类型,如下所示:
enum SomethingKeys {
currentStreak,
longestStreak,
contributionsThisYear,
totalContributions,
currentCompany
}
type Something = {
[key in keyof typeof SomethingKeys]: { display: string, value: number | string };
}虽然使用接口更容易阅读和维护。
发布于 2022-04-17 18:49:34
您可以显式定义第二部分。
type DataPoint = {
display: string;
value: number;
};
export type Something = {
[key in keyof typeof VALUES]: DataPoint;
};https://stackoverflow.com/questions/71904552
复制相似问题