I'm trying to use type safety for a specific scenario. Imagine we have:
const enum Color {
red = 'red',
blue = 'blue',
}
const enum Shape {
rectangle = 'rectangle',
square = 'square',
circle = 'circle'
}
Is it possible to create a type that would accept either the values of the first enum or the second?
What I've tried:
type Characteristics =
| `${Color}`
| `${Shape}`
const characteristic: Characteristics[] = ['circle', 'red']; // should fail, but it does not
But I couldn't fully satisfy my requirements as that array can take any of the enum values.
What I need is:
const char1: Characteristics[] = ['circle', 'square']; // good
const char2: Characteristics[] = ['circle', 'red']; // fail
const char3: Characteristics[] = []; // fail
const char4: Characteristics[] = ['test', 'red', 'blue']; // fail
Use a Union Type
(keyof typeof Color)[] | (keyof typeof Shape)[]
to declare an array type with items either only of typeColor
or only of typeShape
.To ensure that the array has at least one value declare a Tuple Type with a fixed first item and a spreaded array on the second index.
TypeScript Playground