Reputation: 7113
Currently I do:
export const CValidEbookTypes = ['epub', 'mobi', 'pdf', 'azw3', 'txt', 'rtf'];
export type IEbookType = 'epub' | 'mobi' | 'pdf' | 'azw3' | 'txt' | 'rtf';
to have an array of valid book types and a typescript type, that defines them. This look quite redundant.
Is there a way to define the type using the array? My goal is obviously to avoid writing the book type twice. So any other solution would also be welcome.
Upvotes: 1
Views: 66
Reputation: 3547
By using as const
, typescript infers the string literals as type for CValidEbookTypes
. Then you can use 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"
Upvotes: 2