Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.