TypeScript tutorial: Lesson 19 – Literal Types


There are three sets of literal types available in TypeScript today: strings, numbers, and booleans; by using literal types you can allow an exact value which a string, number, or boolean must have.

Literal Narrowing

When you declare a variable via var or let, you are telling the compiler that there is the chance that this variable will change its contents. In contrast, using const to declare a variable will inform TypeScript that this object will never change.

// We're making a guarantee that this variable
// constString will never change, by using const.

// So, TypeScript sets the type to be "Tutorialspots" not string
const constString = "Tutorialspots"

// On the other hand, a let can change, and so the compiler declares it a string
let variableString = "Can change"

String Literal Types

In practice string literal types combine nicely with union types, type guards, and type aliases. You can use these features together to get enum-like behavior with strings.

type acceptTags = "input" | "select" | "button" | "textarea"

var tag:acceptTags = "input"
//var tag_error:acceptTags = "invalid" //error TS2322: Type '"invalid"' is not assignable to type 'acceptTags'.

Numeric Literal Types

type availableSizes = 14 | 16 | 18

var size1:availableSizes = 14
//size1 = 20 //error TS2322: Type '20' is not assignable to type 'availableSizes'.
var size2 = 18 as availableSizes

Boolean Literal Types

interface ValidationSuccess {
  isValid: true;
  reason: null;
};

interface ValidationFailure {
  isValid: false;
  reason: string;
};

type ValidationResult =
  | ValidationSuccess
  | ValidationFailure;

Leave a Reply