我想定义一个接口,该接口的键值可以是字符串数组。但是这些字符串只能来自已定义的字符串数组。
类似-
const valueOptions = ['a','b','c',.... 100 more];
interface containerProps {
key: <array of strings which can only be a subset of valueOptions>
}
请帮助。
我想定义一个接口,该接口的键值可以是字符串数组。但是这些字符串只能来自已定义的字符串数组。
类似-
const valueOptions = ['a','b','c',.... 100 more];
interface containerProps {
key: <array of strings which can only be a subset of valueOptions>
}
请帮助。
您可以提取类型,然后将其映射到您的界面上
// 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","c"
因此,根据您的情况,您将使用number
,因为您不查找任何特定的索引:
const valueOptions = <const>["a","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[];
}