gpt4 book ai didi

javascript - typescript :如何使用其值为数组中值子集的键定义接口(interface)?

转载 作者:行者123 更新时间:2023-11-29 15:07:05 29 4
gpt4 key购买 nike

我想定义一个接口(interface),它有一个键,其值可以是一个字符串数组。但这些字符串只能来自已定义的字符串数组。

有点像 -

const valueOptions = ['a', 'b', 'c', .... 100 more];

interface containerProps {
key: <array of strings which can only be a subset of valueOptions>
}

请帮忙。

最佳答案

首先使用 <const> 锁定数组项断言,因此它们是有限集。

现在您可以使用索引值类型了。例如:

  • typeof valueOptions[0]只能是"a"
  • typeof valueOptions[1]只能是"b"
  • typeof valueOptions[number]可以是 "a", "b", "c"

因此对于您的上下文,您将使用 number因为您不是在寻找任何特定索引:

const valueOptions = <const>["a", "b", "c"]; // lock it down with const assertion

interface IContainerProps {
key: typeof valueOptions[number]; // typeof index members of valueOptions
}

const a: IContainerProps = {
key: "b"
};

所以对于小的子集你可以创建一个联合类型:

interface IContainerProps {
key: typeof valueOptions[1] | typeof valueOptions[2];
}

const a: IContainerProps = {
key: "b"
};

const b: IContainerProps = {
key: "c"
};

关于javascript - typescript :如何使用其值为数组中值子集的键定义接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58860846/

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