Ask Your Question
1

How can a union type be defined in TypeScript using an array of strings?

asked 2023-06-26 23:22:58 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-06-26 23:37:02 +0000

scrum gravatar image

A union type can be defined in TypeScript using an array of strings by using the | operator to separate the elements of the array. For example:

type MyUnionType = 'string1' | 'string2' | 'string3';

This creates a type MyUnionType that can be one of three string values: 'string1', 'string2', or 'string3'.

If the strings are retrieved dynamically from an array, they can be used with a ReadonlyArray and the typeof operator to infer the union type. For example:

const strings = ['string1', 'string2', 'string3'] as const;
type MyUnionType = typeof strings[number];

This creates a type MyUnionType that can be one of the three string values in the strings array. The as const assertion is necessary to ensure that the array is treated as a readonly tuple rather than a regular array.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-26 23:22:58 +0000

Seen: 10 times

Last updated: Jun 26 '23