只能包含特定列表中的元素的数组的 Typescript 类型

Leo*_*ssi 4 javascript enums typescript ecmascript-6 typescript-typings

我想声明一个数组的类型,最多可以包含以下字符串之一:'first', 'second', 'third'

该数组的一些有效示例:

  • []
  • [ 'first' ]
  • [ 'first', 'second' ]
  • [ 'first', 'second', 'third' ]
  • [ 'first', 'third' ]
  • [ 'second', 'third' ]

一些无效的数组:

  • [ 'other-value' ]// 不应接受其他值
  • [ 'first', 'first' ]// 不接受重复项

我写过的类型:

export enum MyOptions {
  first = 'first',
  second = 'second',
  third = 'third'
}

export type MyType = {
  name: string;
  email: string;
  listings: {
   MyOptions;
  }[];
};
Run Code Online (Sandbox Code Playgroud)

它有一条警告,指出成员“MyOptions”隐式具有“任意”类型,但可以从使用中推断出更好的类型

那么如果改成:

export type MyType = {
  name: string;
  email: string;
  listings: {
   options: MyOptions;
  }[];
};
Run Code Online (Sandbox Code Playgroud)

现在,没有警告,但它具有options我认为不必添​​加的额外价值。

有什么方法可以解决这个问题吗?

小智 6

您可以使用Set数据结构。

export type Options = 'first' | 'second' | 'third'
export type Listing = Set<Options>

export type MyType = {
    name: string;
    email: string;
    listings: Listing;
};

const myType = {
  name: 'name',
  email: 'email',
  listing: new Set(['first', 'second'])
}
Run Code Online (Sandbox Code Playgroud)

然后您将确保列表中没有重复的选项。注意:实际上你可以传递重复的选项,但Set会忽略它们。