Search⌘ K

Literal Type, Narrowing, and Const

Explore how TypeScript uses literal types to restrict variables to specific values, and how type narrowing leverages discriminants to refine union types. Understand the distinctions between const and let in defining literal types and how these features enhance type safety and control within your code.

Literal type #

A literal type sets a single value to a variable’s type. Initially, TypeScript supported only a string. Nowadays, a literal type can be a Boolean, a number, or an enum.

TypeScript 3.3.4
let x : "test";
let y : 123;
let z : true;

The concept of having a value that controls the data type flow can be extended beyond type checking in order to narrow down to a single type within a union. A return type can borrow the concept of narrowing by depending on the value’s discriminant field. The result is a ...