繁体   English   中英

Typescript:如何从字符串数组定义类型?

[英]Typescript: How can I define a type from an string array?

目前我这样做:

export const CValidEbookTypes = ['epub', 'mobi', 'pdf', 'azw3', 'txt', 'rtf'];
export type IEbookType = 'epub' | 'mobi' | 'pdf' | 'azw3' | 'txt' | 'rtf';

拥有一组有效的书籍类型和一个定义它们的 typescript 类型。 这看起来很多余。

有没有办法使用数组定义类型? 我的目标显然是避免将书型写两次。 因此,任何其他解决方案也将受到欢迎。

通过使用as const ,typescript 将字符串文字推断为CValidEbookTypes的类型。 然后你可以使用typeof CValidEbookTypes[number]

export const CValidEbookTypes = ['epub', 'mobi', 'pdf', 'azw3', 'txt', 'rtf'] as const;
export type IEbookType = typeof CValidEbookTypes[number];
// IEbookType will be "epub" | "mobi" | "pdf" | "azw3" | "txt" | "rtf"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM