繁体   English   中英

TypeScript:如何使用嵌套对象定义类型

[英]TypeScript: How to define a type with nested objects

我正在尝试定义这个 object 类型。

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;
};

在您当前的类型定义中,您具有以下内容:

export type Color = {
    [colorName: string]: string;
};

上面的代码等同于:

export type Color = Record<string, string>

相反,您应该在类型定义中明确定义每个字段。 定义Record指定 object 的键类型和值类型,但不指定每个键的名称或每个值的类型(以防某些键具有其他数据类型)。

在这种情况下,您正在寻找一个接口:

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键为 object 且键名具有任意值,那么您可以改为这样做:

modes: Record<string, SimpleColorDefinition>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM