Categories
TypeScript Answers

How to define string literal union type from constants in TypeScript?

Spread the love

Sometimes, we want to define string literal union type from constants in TypeScript.

In this article, we’ll look at how to define string literal union type from constants in TypeScript.

How to define string literal union type from constants in TypeScript?

To define string literal union type from constants in TypeScript, we can use the typeof operator on the constants and join the types returned together with |.

For instance, we write

const MY_CONSTANT = "MY_CONSTANT";
const SOMETHING_ELSE = "SOMETHING_ELSE";
type MyType = typeof MY_CONSTANT | typeof SOMETHING_ELSE;

to define 2 constants MY_CONSTANT and SOMETHING_ELSE.

Then we get their types with typeof.

Finally, we create the union type with the returned types with | and assign the expression to MyType.

Conclusion

To define string literal union type from constants in TypeScript, we can use the typeof operator on the constants and join the types returned together with |.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *