Learning TypeScript 2.x
上QQ阅读APP看书,第一时间看更新

Literal types

Literal types allow us to declare the exact value that a string Boolean or number must have. When we declare a variable using the let keyword, its value will be inferred as a primitive type:

let five = 5; // number
let falsy = false; // boolean
let shape = "rectangle"; // string

However, if we use the const keyword, the type is inferred as the actual assigned value:

const five = 5; // 5
const falsy = false; // false
const shape = "rectangle"; // rectangle

Literal types can be used in combination with union types, type guards, and type aliases with ease:

type ShapeKind = "square" | "rectangle" | "circle";

Literal types can be used in combination with type guards and the power of control flow analysis to narrow union types using a technique known as discriminated unions.