目前我这样做:
export const CValidEbookTypes = ['epub', 'mobi', 'pdf', 'azw3', 'txt', 'rtf'];
export type IEbookType = 'epub' | 'mobi' | 'pdf' | 'azw3' | 'txt' | 'rtf';拥有一个有效书籍类型的数组和一个typescript类型,它定义了它们。这看起来非常多余。
有没有办法使用数组来定义类型?我的目标显然是避免两次编写图书类型。因此,任何其他解决方案也将受到欢迎。
发布于 2020-08-22 17:55:19
通过使用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"https://stackoverflow.com/questions/63534787
复制相似问题