Ste*_*art 14 typescript typescript2.0
基于字符串数组制作 TypeScript 类型的最佳方法是什么?我使用的是 2.6.2 版。该数组很长,我不想通过复制 Enum 声明中的字符串值来重复自己。
我想做的是这样的:
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
export type Color = convertStringArrayToType(colors);
Run Code Online (Sandbox Code Playgroud)
以下解决方案(源代码)工作正常,但感觉很糟糕:
/** 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;
Run Code Online (Sandbox Code Playgroud)
Gui*_*oli 28
从 Typescript 3.4 开始,您可以使用as const并从数组生成联合类型,如下所示
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'] as const;
export type Color = typeof colors[number]; // 'red'|'orange'|'yellow'|'green'|'blue'|'indigo'|'violet'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7811 次 |
| 最近记录: |