且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从 TypeScript 中的字符串数组创建类型?

更新时间:2022-06-23 05:29:55

从 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'