TypeScript数组为字符串文字类型 [英] TypeScript array to string literal type

查看:973
本文介绍了TypeScript数组为字符串文字类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我的应用程序中同时需要这两个功能,但是我试图将代码保持DRY.那么,有什么方法可以从另一个推论吗?

我基本上想说类似type Furniture = [any string in furniture array]之类的东西,所以没有重复的字符串.

解决方案

TypeScript 3.0更新:

使用通用的rest参数,有一种方法可以正确地将string[]推断为文字元组类型,然后获取文字的并集类型.

它是这样的:

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

有关通用休息参数的更多信息

TypeScript 3.4更新:

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

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

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

在此PR中以及在发行说明.. >

I currently have both an array of strings and a string literal union type containing the same strings:

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

I need both in my application, but I am trying to keep my code DRY. So is there any way to infer one from the other?

I basically want to say something like type Furniture = [any string in furniture array], so there are no duplicate strings.

解决方案

Update for TypeScript 3.0 :

With the use of generic rest parameters, there is a way to correctly infer string[] as a literal tuple type and then get the union type of the literals.

It goes like this:

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

More about generic rest parameters

Update for TypeScript 3.4:

TypeScript version 3.4 has introduced so-called const contexts, which is a way to declare a tuple type as immutable and get the narrow literal type directly (without the need to call a function like shown above).

With this new syntax, we get this nice concise solution:

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

More about the new const contexts is found in this PR as well as in the release notes.

这篇关于TypeScript数组为字符串文字类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆