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"
extendshere means "fits into", not inheriting like in an interface or a class."hello"fits intostring, so the result is"yes".- When
Tis a union, the formula runs for each member one at a time, then the results are joined again:stringgives"yes",numbergives"no", so the total is"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 |
- To the right of the colon you write the new type for each key.
stringmeans everything becomes a string.T[K]means "its old type", so the type doesn't change. readonlyin front makes every property unchangeable. Iffrozenhas the typeFrozen<Product>,frozen.price = 20is rejected witherror TS2540: Cannot assign to 'price' because it is a read-only property.?after the key makes every property optional.PartialandReadonlyfrom the utility types lesson are built exactly this way.
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" | ...
- A union inside
${}also runs member by member: 3 event names give 3 handler names. Capitalizeis a built-in type that makes the first letter uppercase, so"click"becomes"Click".- Two unions in one template give every combination.
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
- Forgetting
inin a mapped type. The right form is[K in keyof T]. Withoutin, the code is not a mapped type anymore, and TypeScript rejects it. - Forgetting a union runs member by member.
IsString<string | number>isn't"no", it's"yes" | "no". Object.keyswithoutas. It givesstring[], so TS2322. In the exercise, TypeScript checks your code, so this error appears in the console and makes the exercise fail. Writeas (keyof T)[].keyson an object from outside. Say there'stype Position = { x: number; y: number }.const pos: Position = pis accepted even whenpalso hascolor: "red", because an object may have extra keys (extra keys are rejected only in an object literal, andpis a variable). Sokeys(pos)also holds"color", and a loop that callspos[k].toFixed(1)stops atcolor:TypeError: pos[k].toFixed is not a function.- Thinking these types check data. Every advanced type is gone when the code runs, like any other type. Data from outside still has to be checked with a type guard.
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.