Skip to main content

String Literals

January 30, 2024Less than 1 minute

String Literals

  • You can use a string literal as a type

Example

type CardinalDirection =
| "North"
| "East"
| "South"
| "West";

function move(distance: number, direction: CardinalDirection) {
    console.log('moving');
}

move(1,"North"); // Okay
move(1,"Nurth"); // Error!
  • We define a new type CardinalDirection that can be one of the values "North", "East", "South" and `"West"
  • If we expect this type as a function parameter, we can only pass one of these values, otherwise we get an error