Categories
TypeScript Answers

How to derive union type from tuple or array values with TypeScript?

Spread the love

Sometimes, we want to derive union type from tuple or array values with TypeScript.

In this article, we’ll look at how to derive union type from tuple or array values with TypeScript.

How to derive union type from tuple or array values with TypeScript?

To derive union type from tuple or array values with TypeScript, we can use the typeof operator.

For instance, we write

const list = ["a", "b", "c"] as const;
type UnionType = typeof list[number];

to create the list array with some values inside.

Then we use the list to create a union type of the list values with typeof list[number].

And we assign that to UnionType.

Therefore, any UnionType variable must be set to value 'a', 'b', or 'c'.

Conclusion

To derive union type from tuple or array values with TypeScript, we can use the typeof operator.

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 *