gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:50:57 24 4
gpt4 key购买 nike

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

该数组的一些有效示例:

  • []
  • ['first']
  • ['first', 'second']
  • ['first', 'second', 'third']
  • ['第一','第三']
  • ['第二','第三']

一些无效的数组:

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

我写过的类型:

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

export type MyType = {
name: string;
email: string;
listings: {
MyOptions;
}[];
};

它有一个警告说Member 'MyOptions' 隐含了一个'any' 类型,但是可以从使用中推断出更好的类型

所以如果改成:

export type MyType = {
name: string;
email: string;
listings: {
options: MyOptions;
}[];
};

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

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

最佳答案

您可以使用 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'])
}

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

关于javascript - 只能包含特定列表中的元素的数组的 typescript 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73359550/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com