TypeScript数组到字符串文字类型

问题描述 投票:7回答:3

我目前有一个字符串数组和一个包含相同字符串的字符串文字联合类型:

const furniture = ['chair', 'table', 'lamp'];
type Furniture = 'chair' | 'table' | 'lamp';

我在我的应用程序中需要两个,但我试图保持我的代码DRY。那么有没有办法从另一个推断出一个?

我基本上想说像type Furniture = [any string in furniture array]这样的东西,所以没有重复的字符串。

arrays string typescript types
3个回答
30
投票

TypeScript 3.0更新:

通过使用通用rest参数,有一种方法可以正确地将string[]推断为文字元组类型,然后获得文字的联合类型。

它是这样的:

const tuple = <T extends string[]>(...args: T) => args;
const furniture = tuple('chair', 'table', 'lamp');
type Furniture = typeof furniture[number];

More about generic rest parameters

TypeScript 3.4的更新:

TypeScript版本3.4引入了所谓的const上下文,这是一种将元组类型声明为不可变的方法,并直接获取窄文字类型(无需调用如上所示的函数)。

使用这种新语法,我们得到了这个简洁的解决方案:

const furniture = <const> ['chair', 'table', 'lamp'];
type Furniture = typeof furniture[number];

More about the new const contexts is found in this PR以及release notes


9
投票

最好的解决方法:

const furnitureObj = { chair: 1, table: 1, lamp: 1 };
type Furniture = keyof typeof furnitureObj;
const furniture = Object.keys(furnitureObj) as Furniture[];

理想情况下,我们可以这样做:

const furniture = ['chair', 'table', 'lamp'];
type Furniture = typeof furniture[number];

不幸的是,今天furniture被推断为string[],这意味着Furniture现在也是string

我们可以使用手动注释强制打字作为文字,但它会带来重复:

const furniture = ["chair", "table", "lamp"] as ["chair", "table", "lamp"];
type Furniture = typeof furniture[number];

TypeScript issue #10195跟踪提示TypeScript的能力,列表应该被推断为静态元组而不是string[],所以将来可能会这样。


-1
投票

我建议的唯一调整是使const保证与类型兼容,如下所示:

type Furniture = 'chair' | 'table' | 'lamp';

const furniture: Furniture[] = ['chair', 'table', 'lamp'];

如果您在数组中出现拼写错误,或者添加未知项,则会发出警告:

// Warning: Type 'unknown' is not assignable to furniture
const furniture: Furniture[] = ['chair', 'table', 'lamp', 'unknown'];

唯一没有帮助的情况是数组中没有包含其中一个值的情况。

© www.soinside.com 2019 - 2024. All rights reserved.