I have defined a type called Direction
, which is a union of the strings 'LEFT'
and 'RIGHT'
. However, TypeScript (tsc) is giving me an error when I try to assign a 'LEFT'
string to it. Here's the code snippet:
type Direction = 'LEFT' | 'RIGHT';
class Duckling {
direction: Direction;
constructor() {
// ERROR: Type 'string' is not assignable to type 'Direction'
this.direction = ['LEFT', 'RIGHT'][Math.floor(Math.random() * 2)];
}
}
What misconception do I have about TypeScript types here? Shouldn't this.direction
accept a string if it's either 'LEFT'
or 'RIGHT'
?
(Note: I prefer not to use enums in this case. I'm looking for an explanation on why this approach doesn't work.)
Interestingly, adding as Direction
at the end seems to resolve the issue:
// This works fine:
this.direction = ['LEFT', 'RIGHT'][Math.floor(Math.random() * 2)] as Direction;