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

时间:2020-08-22 09:45:19

标签: javascript arrays typescript types

我目前正在这样做:

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

具有一组有效的书本类型和一个用于定义它们的打字稿类型。这看起来很多余。

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

1 个答案:

答案 0 :(得分:2)

通过使用TextField,typescript将字符串文字推断为as const的类型。然后,您可以使用CValidEbookTypes

typeof CValidEbookTypes[number]