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

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

问题描述

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

const Furniture = ['chair', 'table', 'lamp'];type 家具 = '椅子' |'表' |'灯';

我的应用程序中需要两者,但我试图保持我的代码干燥.那么有没有办法从另一个推断一个?

我基本上想说类似type Furniture = [家具数组中的任何字符串],所以没有重复的字符串.

解决方案

TypeScript 3.0 更新:

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

事情是这样的:

const tuple = (...args: T) =>参数;const Furniture = tuple('椅子', '桌子', '灯');家具类型 = 家具类型[数量];

更多关于通用休息参数

TypeScript 3.4 更新:

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

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

const Furniture = ['chair', 'table', 'lamp'] as const;家具类型 = 家具类型[数量];

在此 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天全站免登陆