如何创建具有动态字符串联合属性名称的记录,这些属性是可选的?

huangapple go评论48阅读模式
英文:

How to create Record with dynamic string union property names that are optional?

问题

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

我想创建下面更长的语法的等价物,但是否有一种方法使它具有可选属性,以便我可以轻松添加/删除这些选项?

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

我正在尝试找到一种使以下无效代码生效的方法。

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

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

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

但是 TypeScript 对 MyObj 给出以下错误 TS Playground 链接

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

英文:

I want to define an object type where the property names are pre-defined, but also optional.

I want to create the equivalent of the below longer syntax, but is there a way to make it dynamic with optional properties so I could easily add / remove those options?

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

I'm trying to find a way to make the following invalid code work.

type options = &#39;one&#39; | &#39;two&#39; | &#39;three&#39;;
type List = Record&lt;options, string&gt;;

// Valid
const MyObjOne: List = {
    one: &#39;Value 1&#39;,
    two: &#39;Value 2&#39;,
    three: &#39;Value 3&#39;,
}

// Invalid
const MyObjTwo: List = {
  one: &#39;Value 1&#39;,
  two: &#39;Value 2&#39;,
}

But TypeScript gives this error for MyObj TS Playground link

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

答案1

得分: 1

使用实用程序类型Partial

type List = Partial<Record<options, string>>;
英文:

Use the utility type Partial:

type List = Partial&lt;Record&lt;options, string&gt;&gt;;

huangapple
  • 本文由 发表于 2023年2月6日 17:52:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75359725.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定