[英]Typescript: How to define an interface with a key whose value is a subset of values in an array?
我想定义一个接口,它的键的值可以是字符串数组。 但这些字符串只能来自已定义的字符串数组。
就像是 -
const valueOptions = ['a', 'b', 'c', .... 100 more];
interface containerProps {
key: <array of strings which can only be a subset of valueOptions>
}
请帮忙。
您可以提取类型,然后将 map 提取到您的界面上,如下所示
// declare "as const" to make it a readonly Array<"a"|"b"|"c"> instead of string[]
const valueOptions = ["a", "b", "c"] as const;
// Type helper to extract the underlying data type of the array
type StripArray<T extends ReadonlyArray<string>> = T extends ReadonlyArray<infer U> ? U : never;
type ValueUnion = StripArray<typeof valueOptions>; // ValueUnion = "a"|"b"|"c";
interface Whatever {
keys: ValueUnion[] // Whatever.keys is Array<"a"|"b"|"c">
}
我在 TS 游乐场页面上做了很多此类事情,这对于快速查看类型和查看实际发生的情况非常有帮助。
首先使用<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"
};
enum KeyOptions {
A = ‘a’,
B = ‘b’
}
interface ArrayAndStuff {
key: KeyOptions[];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.