Literal types

Literal types#

A literal type accepts exactly one value.

Union of string literals.

type Method = "GET" | "POST" | "PUT" | "DELETE";
const m: Method = "GET";

Union of number literals.

type Port = 80 | 443 | 8080;

as const narrows every property to its literal form.

const cfg = {host: "0.0.0.0", port: 80} as const;
//    ^? { readonly host: "0.0.0.0"; readonly port: 80 }

Template literal types#

Combine literal types with ${ } placeholders to compute new literal types.

A composed literal from a list.

type Lang  = "en" | "es" | "fr";
type Greet = `hello-${Lang}`;          // "hello-en" | "hello-es" | "hello-fr"

Using built-in case mappers.

type EventName = `on${Capitalize<string>}`;

References#