Javascript 如何从字符串数组定义类型?
目前我有:Javascript 如何从字符串数组定义类型?,javascript,arrays,typescript,types,Javascript,Arrays,Typescript,Types,目前我有: export const CValidEbookTypes = ['epub', 'mobi', 'pdf', 'azw3', 'txt', 'rtf']; export type IEbookType = 'epub' | 'mobi' | 'pdf' | 'azw3' | 'txt' | 'rtf'; 要获得有效图书类型数组和定义它们的typescript类型。这看起来很多余 有没有办法使用数组定义类型? 我的目标显然是避免写两次书。因此,任何其他解决方案都是受欢迎的。通过使用
export const CValidEbookTypes = ['epub', 'mobi', 'pdf', 'azw3', 'txt', 'rtf'];
export type IEbookType = 'epub' | 'mobi' | 'pdf' | 'azw3' | 'txt' | 'rtf';
要获得有效图书类型数组和定义它们的typescript类型。这看起来很多余
有没有办法使用数组定义类型?
我的目标显然是避免写两次书。因此,任何其他解决方案都是受欢迎的。通过使用
作为常量,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"
您可以使用CValidEbookTypes[number]
,但需要在数组后添加as const
,以将类型推断为文本。