1

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.

1
  • 1
    You can use CValidEbookTypes[number], but you need to add as const after the array to infer the types as literals. Commented Aug 22, 2020 at 9:50

1 Answer 1

2

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"

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.