我试图定义这个对象类型。
colors: {
text: "#343D48", // body color and primary color
text_secondary: "#02073E", // secondary body color
heading: "#565F67", // primary heading color
heading_secondary: "#0F2137", // heading color
background: "#FFFFFF", // body background color
background_secondary: "#F9FBFD", // secondary background color
border_color: "#E5ECF4", // border color
primary: "#78F0AC", // primary button and link color
secondary: "#29CC5F", // secondary color - can be used for hover states
muted: "#7B8188", // muted color
dark: "#343D48",
accent: "#609", // a contrast color for emphasizing UI
yellow: "#F6C416",
error: "#F65241",
// highlight a background color for highlighting text
modes: {
dark: {
text: "#fff",
background: "#000",
primary: "#0cf",
secondary: "#09c",
muted: "#111",
},
},
},这就是我到目前为止所写的,我不知道如何用TypeScript定义嵌套对象。如何定义上述代码的类型?到目前为止,这就是我所拥有的:
export type Color = {
[colorName: string]: string;
};发布于 2022-05-30 01:45:12
在当前类型定义中,有以下内容:
export type Color = {
[colorName: string]: string;
};上述代码与以下内容相同:
export type Color = Record<string, string>相反,您应该清楚地定义类型定义中的每个字段。定义Record指定对象的键类型和值类型,但没有指定每个键的名称或每个值的类型(如果某些键有另一种数据类型)。
在本例中,您正在寻找一个接口:
export interface ColorDefinition {
text: string;
text_secondary: string;
heading: string;
heading_secondary: string;
background: string;
background_secondary: string;
border_color: string;
primary: string;
secondary: string;
muted: string;
dark: string;
accent: string;
yellow: string;
error: string;
modes: {
dark: {
text: string;
background: string;
primary: string;
secondary: string;
muted: string;
};
};
}
export type { ColorDefinition };同样,您也可以使用type定义接口:
type ColorDefinition = {
primary: string;
...
}
export type { ColorDefinition };如果您想要正确地编写这个接口(因为您有重复的键值对),我将这样编写您的类型定义:
interface SimpleColorDefinition {
text: string;
background: string;
primary: string;
secondary: string;
muted: string;
}
interface UIColorDefinition extends SimpleColorDefinition {
text_secondary: string;
heading: string;
heading_secondary: string;
background_secondary: string;
border_color: string;
dark: string;
accent: string;
yellow: string;
error: string;
modes: {
dark: SimpleColorDefinition;
};
}如果您希望modes键是一个具有键名值的对象,那么您可以这样做:
modes: Record<string, SimpleColorDefinition>https://stackoverflow.com/questions/72428242
复制相似问题