union of enum to union literal of enum type in typescript

To create a union of enum and a union literal of enum type in TypeScript, you can define a type that combines the enum type with a type literal of the enum values that you want to use in the union.

Here's how you can do it:

index.ts
enum Color {
  Red = 'red',
  Green = 'green',
  Blue = 'blue',
}

type ColorUnion = Color | 'orange' | 'yellow';

function printColor(color: ColorUnion) {
  console.log(`The selected color is ${color}`);
}

printColor(Color.Green); // Output: The selected color is green
printColor('orange'); // Output: The selected color is orange
334 chars
15 lines

In the example above, we define an enum type called Color. We then define a type called ColorUnion that combines the Color enum type with the string literals 'orange' and 'yellow'. Finally, we define a function printColor that takes an argument of type ColorUnion and logs the selected color to the console.

Note that the ColorUnion type is a union of the Color enum and the string literals 'orange' and 'yellow'. This means that the printColor function can accept any value that is either a Color value or the string 'orange' or 'yellow'.

gistlibby LogSnag