Literal Types

A literal type is a more specific sub-type of a collective type. A literal type can represent an exact value, such as a specific number or string, instead of a general value that can be any number or string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const numberLiteral: 72 = 72;
const stringLiteral: "Benny" = "Benny";
const booleanLiteral: true = true;
const objectLiteral = {
age: 35,
name: 'Benny'
};

enum ConnectionState {
OFF,
ON
}

const enumLiteral = ConnectionState.OFF;

Literal Narrowing

Narrowing refers to the process of reducing the set of possible values that a variable can hold. TypeScript applies literal narrowing, when declaring a variable with the const keyword:

1
2
// Type of "text" is "Hello, World!" (string literal)
const text = "Hello, World!";

On the other hand, when using the let keyword, TypeScript will infer a collective type such as number for the variable:

1
2
// Type of "text" is "string" (collective type)
let text = "Hello, World!";