将TypeScript字符串字面量类型转换为字符串数组

13

我有

type ImageVerticalSpacing = 'ignoreBottom' | 'ignoreTop' | 'ignoreBoth' 
| 'Default';

我在 TypeScript 中需要将这些字符串作为字符串数组传递给下拉列表。如何将类型 ImageVerticalSpacing 转换为字符串数组?

3个回答

12
建立在jcal's answer基础之上并重申:“你无法在TypeScript中将类型转换为运行时的值。但是你可以反过来:创建一个运行时对象,并让TypeScript推断其类型。”@steve-holgado有一篇很棒的博客文章,介绍了如何使用const assertions来实现这个目的:https://steveholgado.com/typescript-types-from-arrays/ 通过TypeScript 3.4+的const assertions,你可以这样做:
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];

6
您无法在TypeScript中将类型转换为运行时的值。但您可以做反向操作:创建一个运行时对象并让TypeScript推断其类型。
用于此目的的理想运行时对象应该是元组。不幸的是,TypeScript本身并不能很好地推断元组。我使用一个叫做tuple()的辅助函数来返回元组类型。
更新:2018-12,自TypeScript 3.0以来,tuple()函数可以这样编写:
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中看到示例)

希望这能帮到您。祝好运!


0

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"]

游乐场链接


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接