【问题标题】:Define customized type for a nested structure which all have value and label properties为具有值和标签属性的嵌套结构定义自定义类型
【发布时间】:2020-12-11 04:48:22
【问题描述】:

我正在为我们的项目使用打字稿,我需要为以下结构提供一个类型,它可以有任意数量的键,在每个键内,值和标签对于所有选项都是固定的,它们可以是任何字符串输入值。

const MY_OPTIONS = {
  "keep same": {
    value: "keep",
    label: "Option 1 label text"
  },
  "select new": {
    value: "new",
    label: "Option 2 label text"
  }
};

【问题讨论】:

    标签: typescript types typescript-typings


    【解决方案1】:

    应该是这样的:

    interface MY_OPTIONS{
      [key:string]: {
        value: string,
        label: string
      }
    };
    

    【讨论】:

      【解决方案2】:

      替代方案:

      type Option = {
        value: string,
        label: string
      }
      type Options = Record<string, Option>;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-13
        • 1970-01-01
        • 2023-01-12
        • 1970-01-01
        • 1970-01-01
        • 2018-10-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多