我有
type ImageVerticalSpacing = 'ignoreBottom' | 'ignoreTop' | 'ignoreBoth'
| 'Default';
我在 TypeScript 中需要将这些字符串作为字符串数组传递给下拉列表。如何将类型 ImageVerticalSpacing 转换为字符串数组?
我有
type ImageVerticalSpacing = 'ignoreBottom' | 'ignoreTop' | 'ignoreBoth'
| 'Default';
我在 TypeScript 中需要将这些字符串作为字符串数组传递给下拉列表。如何将类型 ImageVerticalSpacing 转换为字符串数组?
const animals = ['cat', 'dog', 'mouse'] as const
type Animal = typeof animals[number]
// type Animal = 'cat' | 'dog' | 'mouse'
所以问题的代码将如下所示:
const imageVerticalSpacing = ['ignoreBottom', 'ignoreTop', 'ignoreBoth', 'Default'];
type ImageVerticalSpacing = typeof imageVerticalSpacing[number];
type Narrowable = string | number | boolean | symbol |
object | {} | void | null | undefined;
const tuple = <T extends Narrowable[]>(...args: T)=>args;
const imageVerticalSpacing = tuple('ignoreBottom','ignoreTop','ignoreBoth','Default');
type ImageVerticalSpacing = (typeof imageVerticalSpacing)[number];
imageVerticalSpacing
对象是一个字符串数组,您可以将其用于下拉菜单。它的类型为 ['ignoreBottom','ignoreTop','ignoreBoth','Default']
。而类型 ImageVerticalSpacing
与您声明的相同,即为 'ignoreBottom' | 'ignoreTop' | 'ignoreBoth' | 'Default'
。
(在Playground中看到示例)
希望这能帮到您。祝好运!
TypeScript 的接口或类型别名在运行时并不存在。因此,您无法在运行时使用它们的值。您可以尝试使用枚举:
enum ImageVerticalSpacing {
ignoreBottom,
ignoreTop,
ignoreBoth,
Default
}
Object.keys(ImageVerticalSpacing).filter(k => isNaN(k as any)) // The filter is to filter out the index keys that TypeScript generates. See the generated JS code
// ["ignoreBottom", "ignoreTop", "ignoreBoth", "Default"]