如何从 TypeScript 中的字符串数组创建类型? [英] How do I create a type from a string array in TypeScript?
本文介绍了如何从 TypeScript 中的字符串数组创建类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基于字符串数组创建 TypeScript 类型的最佳方法是什么?我使用的是 2.6.2 版.数组很长,我不想通过复制 Enum 声明中的字符串值来重复自己.
What is the best way of making a TypeScript type based on an array of strings? I am on version 2.6.2. The array is long and I do not want to repeat myself by duplicating the string values in an Enum declaration.
我想做的是这样的:
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
export type Color = convertStringArrayToType(colors);
以下解决方案 (source) 工作正常,但感觉很黑:
The following solution (source) works fine, but feels hacky:
/** Utility function to create a K:V from a list of strings */
function strEnum<T extends string>(o: Array<T>): {[K in T]: K} {
return o.reduce((res, key) => {
res[key] = key;
return res;
}, Object.create(null));
}
/**
* Sample create a string enum
*/
/** Create a K:V */
const Direction = strEnum([
'North',
'South',
'East',
'West'
])
/** Create a Type */
type Direction = keyof typeof Direction;
推荐答案
从 Typescript 3.4 开始,您可以使用 as const
并从数组中生成联合类型,如下所示
Since Typescript 3.4, you could use as const
and generate a union type from an array as follows
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'] as const;
export type Color = typeof colors[number]; // 'red'|'orange'|'yellow'|'green'|'blue'|'indigo'|'violet'
这篇关于如何从 TypeScript 中的字符串数组创建类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文