【问题标题】:How to create Record with dynamic string union property names that are optional?如何使用可选的动态字符串联合属性名称创建记录?
【发布时间】:2023-02-06 18:18:19
【问题描述】:

我想定义一个对象类型,其中属性名称是预定义的,但也是可选的。

我想创建等同于以下较长语法的语法,但有没有办法通过可选属性使其动态化,以便我可以轻松添加/删除这些选项?

interface List {
  one?: string;
  two?: string;
  three?: string;
}

我试图找到一种方法来使以下无效代码起作用。

type options = 'one' | 'two' | 'three';
type List = Record<options, string>;

// Valid
const MyObjOne: List = {
    one: 'Value 1',
    two: 'Value 2',
    three: 'Value 3',
}

// Invalid
const MyObjTwo: List = {
  one: 'Value 1',
  two: 'Value 2',
}

但是 TypeScript 为 MyObj TS Playground link 给出了这个错误

Property 'three' is missing in type '{ one: string; two: string; }' but required in type 'List'.

【问题讨论】:

    标签: typescript types index-signature


    【解决方案1】:

    使用实用程序类型Partial

    type List = Partial<Record<options, string>>;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-17
      相关资源
      最近更新 更多