gho*_*der 5 javascript typescript typescript-typings
我想定义一个接口,它有一个键,其值可以是字符串数组。但这些字符串只能来自定义的字符串数组。
就像是 -
const valueOptions = ['a', 'b', 'c', .... 100 more];
interface containerProps {
key: <array of strings which can only be a subset of valueOptions>
}
Run Code Online (Sandbox Code Playgroud)
请帮忙。
您可以提取类型,然后将其映射到您的界面上,如下所示
// 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">
}
Run Code Online (Sandbox Code Playgroud)
我在 TS Playground 页面上做了很多这样的事情,这对于快速查看类型并了解实际发生的情况非常有帮助。
| 归档时间: |
|
| 查看次数: |
1099 次 |
| 最近记录: |