Exploring the implementation of type safety in a particular situation. Let’s consider the following:
const enum Color {
red = 'red',
blue = 'blue',
}
const enum Shape {
rectangle = 'rectangle',
square = 'square',
circle = 'circle'
}
Is there a way to create a type that can accept values from either of these enums?
Here's what has been attempted:
type Characteristics =
| `${Color}`
| `${Shape}`
const characteristic: Characteristics[] = ['circle', 'red']; // currently does not fail as intended
However, the requirements were not fully met as the array was able to take any of the enum values.
The desired outcome is:
const char1: Characteristics[] = ['circle', 'square']; // correct
const char2: Characteristics[] = ['circle', 'red']; // should fail
const char3: Characteristics[] = []; // should fail
const char4: Characteristics[] = ['test', 'red', 'blue']; // should fail