Advanced Types — TypeScript

Advanced types build new types from existing ones, with a formula. A conditional type T extends U ? X : Y picks a type: if T fits into U, the result is X, if…

One line, type Frozen<T> = { readonly [K in keyof T]: T[K] }, makes a read-only version of any type: Product, User, whatever you put in. It looks scary, but it's only a formula. You put one type in, and a new type comes out.

That's what advanced types are: building new types from existing ones, with a formula. It's like a formula in a spreadsheet: column B holds a formula based on column A, so when column A changes, column B changes with it, without you rewriting it. Column A is the type you put in (like Product), the formula is an advanced type like Frozen<T>, and column B is the new type that comes out. There are four main tools: conditional types, mapped types, template literal types, and infer.

Conditional types: pick a type with extends

A conditional type picks a type based on a condition. It looks like JavaScript's ? : operator, but for types: T extends U ? X : Y. It means: if T fits into U, the result is X. If not, the result is Y.

type IsString<T> = T extends string ? "yes" : "no"

type A = IsString<string>          // "yes"
type B = IsString<"hello">         // "yes": "hello" is a string too
type C = IsString<number>          // "no"
type D = IsString<string[]>        // "no": an array of strings isn't a string
type E = IsString<string | number> // "yes" | "no"

Mapped types: change every property with [K in keyof T]

A mapped type builds a new object type by going through every key (property name) of an old type, one at a time. keyof T is the union of all its property names, and [K in keyof T] means "for each key K in that union".

type Product = { name: string; price: number; stock: number }

type Stringify<T> = { [K in keyof T]: string }
type Frozen<T> = { readonly [K in keyof T]: T[K] }
type Optional<T> = { [K in keyof T]?: T[K] }

type S = Stringify<Product>
// { name: string; price: string; stock: string }

This table compares the three mapped types for Product:

Key Product Stringify<Product> Frozen<Product> Optional<Product>
name string string readonly name: string name?: string
price number string readonly price: number price?: number
stock number string readonly stock: number stock?: number

A function often used together with mapped types takes the list of keys of an object. In the exercise, you write this function together with Stringify:

function keys<T extends object>(obj: T): (keyof T)[] {
  return Object.keys(obj) as (keyof T)[]
}

keys({ a: 1, b: 2 })       // ["a", "b"]
keys({ x: 1, y: 2, z: 3 }) // ["x", "y", "z"]
keys({})                   // []

The return type (keyof T)[] means an array of the property names of T. But Object.keys always returns string[], because an object may have extra keys that its type does not list. Without as, TypeScript refuses: error TS2322: Type 'string[]' is not assignable to type '(keyof T)[]'. Here as (from the type assertions lesson) is your promise that there are no other keys, and that promise is safe only for objects you built yourself.

Template literal types: join text at the type level

A template literal type uses backticks like a JavaScript template literal, but what goes inside are types:

type EventName = "click" | "focus" | "submit"

type Handler = `on${Capitalize<EventName>}`
// "onClick" | "onFocus" | "onSubmit"

type ClassName = `${"sm" | "md" | "lg"}-${"red" | "blue"}`
// 3 x 2 = 6 combinations: "sm-red" | "sm-blue" | "md-red" | ...

infer: pull a type out of another type

infer can only be used in the extends part of a conditional type. infer U gives the name U to one part of the shape written after extends. If T matches that shape, U holds the type found in that part:

type ElementOf<T> = T extends (infer U)[] ? U : T

type A = ElementOf<string[]>            // string
type B = ElementOf<(string | number)[]> // string | number
type C = ElementOf<Product[]>           // Product
type D = ElementOf<boolean>             // boolean: not an array, so T as it is

Read it as: "if T is an array of something, call that something U, then return U". (infer U)[] is the same as Array<infer U>. ReturnType from the utility types lesson is also built with infer, to take a function's return type.

⚠️ Type formulas written wrong, or read wrong

TL;DR: Advanced types build new types from existing ones, with a formula. A conditional type T extends U ? X : Y picks a type: if T fits into U, the result is X, if not, Y. For a union, the formula runs member by member. A mapped type { [K in keyof T]: ... } builds a new type from each key (property name): string makes every property a string, T[K] keeps the old type, and readonly or ? makes them all read-only or optional. A template literal type joins text, like `on${Capitalize<E>}`, which turns "click" into "onClick". infer U inside extends takes a type out of the shape that matches, such as the type of an array's items. Object.keys returns string[], so use as (keyof T)[] to give the result the type of T's property names.

⚡ Conditional types: pick a type with extends

Write:

type IsString<T> = T extends string ? "yes" : "no"

type A = IsString<"hello">   // "yes"
type C = IsString<number>    // "no"
Guess first: what does IsString<string | number> give?

"yes" | "no", not "no". When T is a union, IsString runs for each member one at a time, and the results are joined again.

Meaning: A conditional type picks a type based on a condition. It looks like ? : in JavaScript, but for types: if T fits into string, the result is "yes", if not, "no". extends here means "fits into", not inheriting like in an interface or a class.

⚡ Mapped types: change every property

Write:

type Stringify<T> = { [K in keyof T]: string }
type Frozen<T> = { readonly [K in keyof T]: T[K] }

Meaning: A mapped type builds a new type from every property of an old type. [K in keyof T] means "for each key K", that is, for each property name of T. To the right of the colon you write the new type: string makes everything a string, T[K] keeps the old type. readonly in front of [K in keyof T] makes every property read-only, and ? after the ] makes them all optional.

In the exercise, the function keys returns Object.keys(obj), the list of an object's keys. Object.keys gives a string[], so write as (keyof T)[]. If you don't, TypeScript rejects it.

⚡ infer: pull a type out

Write:

type ElementOf<T> = T extends (infer U)[] ? U : T

type A = ElementOf<string[]> // string
type D = ElementOf<boolean>  // boolean

Meaning: If T is an array of something, infer U gives that something the name U, and U is returned. If it isn't an array, T comes back as it is. infer can only be used in the extends part of a conditional type.

What you will learn