Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 96 ยท Type Manipulation

Advanced Type-Level Programming

Go further with TypeScript types - recursive DeepReadonly and Paths, variadic tuple types, branded types, in/out variance annotations, and knowing when to stop.

TypeScript's type system is powerful enough to compute with: you've already looped over keys with mapped types, made decisions with conditional types and parsed strings with template literal types. This lesson puts those pieces together into the techniques you'll find in well-typed libraries: recursive types that walk nested objects, variadic tuple types that type functions over argument lists, branded types that stop you from mixing up two kinds of string, and variance annotations that document how a generic type may be substituted.

It ends with the most important skill of all: recognizing when a clever type costs more than it saves. Every technique here exists to make a public API safer and easier to call. If a type makes code harder to read than the bug it prevents, the simple version wins.

As before, examples prove their claims at compile time with type _t = Expect<Equal<Actual, Expected>>; (see Built-in Utility Types). A run that prints its final line means every check passed.

Recursive object types: DeepReadonly and DeepPartial

The built-in Readonly<T> and Partial<T> only touch the top level. For nested configuration objects, you often want the change to reach every level. A type alias may refer to itself, so the deep versions are short:

TypeScript DeepReadonly and DeepPartial

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The order of the branches in DeepReadonly matters:

  1. Functions are returned unchanged. Functions are objects, so without this branch the mapped type would strip their call signature and they'd no longer be callable.
  2. Arrays become readonly arrays of deep-readonly elements, so push disappears.
  3. Other objects get readonly on every property, recursively.
  4. Primitives stop the recursion.

DeepPartial is simpler but has a quirk worth knowing: because mapped types map arrays element by element, DeepPartial<number[]> is (number | undefined)[]. If you need arrays to stay intact, add an array branch like the one in DeepReadonly. The mergeConfig function also shows the honest cost of deep types: merging nested partial objects needs assertions, because TypeScript can't verify that a spread of partial values produces a complete object.

Paths: every dotted key in an object

Many APIs take a "path" string such as 'author.address.city' to reach into nested data (form libraries, translation files, query builders). A recursive mapped type combined with template literals can produce the union of every valid path, and a second type can look up the value at a path:

TypeScript Typed dot paths

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Paths maps each string key K either to K alone (for leaf values) or to K plus `${K}.${...}` for every path inside it, then indexes the mapped object with [keyof T & string] to collect the results into one union. keyof T & string keeps only string keys, because template literals can't hold symbols.

Typos are now compile errors: get(post, 'author.adress.city') fails with TS2345, and editors offer every valid path as autocompletion. Be aware that for large or recursive types (a tree whose nodes contain nodes) the number of paths explodes or never ends. Libraries that use this pattern usually cap the depth with a counter.

Variadic tuple types

A variadic tuple type spreads one tuple type into another: [...A, ...B]. When A and B are type parameters, TypeScript infers them from actual tuples, which lets you type functions that combine or split argument lists precisely:

TypeScript Variadic tuples: concat and partial application

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Two details make this work. Writing the parameter as a: [...A] instead of a: A is a hint that tells TypeScript to infer a tuple ([number, string]) rather than an array ((string | number)[]). And in partial, TypeScript infers First = [currency: string] from the extra arguments, then matches the rest of formatPrice's parameters to Rest, keeping their names. The result euros has the signature (amount: number, decimals: number) => string.

A rest element can appear anywhere in a tuple, not just at the end, as _t2 shows: [string, ...number[], boolean] is "a string, any number of numbers, then a boolean". You saw named and optional tuple elements in Arrays and Tuples.

Branded types

TypeScript's typing is structural: two types with the same shape are interchangeable. Usually that's what you want, but sometimes two values share a representation and must not be mixed. A UserId and an OrderId are both strings; passing one where the other is expected is a real bug that string can't catch.

A brand adds a phantom property that exists only in the type system:

TypeScript Branded IDs (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The last two calls fail on purpose, so nothing runs:

TEXT
main.ts(26,13): error TS2345: Argument of type 'UserId' is not assignable to parameter of type 'OrderId'.
main.ts(27,13): error TS2345: Argument of type 'string' is not assignable to parameter of type 'OrderId'.

(The real output adds indented lines below each error; for the first one they explain that the brand "UserId" is not assignable to "OrderId".) Even a string literal is rejected: a plain string has no brand, so only the constructor functions can produce an OrderId. Delete those two lines and the program prints cancelling o_1001.

How it works:

  • declare const brand: unique symbol; declares a symbol type without creating any value; declare emits no JavaScript at all. Using a unique symbol as the key means no real object can accidentally have the property, and it doesn't show up in autocompletion for normal string keys.
  • Brand<string, 'UserId'> is "a string that also has a [brand] property of type 'UserId'". At runtime the value is a plain string; the extra property is a fiction the compiler maintains.
  • The only way to get a UserId is through userId(), the constructor function. That makes it the natural place for validation: a branded type can mean "this string has been checked".

Brands are a good fit for IDs, units (Meters vs Feet), and validated strings like Email or SanitizedHtml. The type compatibility lesson explains the structural rules that brands opt out of.

Variance annotations: in and out

Variance describes how a generic type's assignability follows its type argument. If Producer<'a'> can be used where Producer<string> is expected, Producer is covariant in T (it produces T values). If Consumer<string> can be used where Consumer<'a'> is expected, it's contravariant (it consumes T values). The type compatibility lesson explains the idea with arrays and callbacks.

TypeScript normally measures variance by comparing the structure of the type. Since TypeScript 4.7 you can also declare it on a type parameter with out (covariant), in (contravariant) or in out (invariant). The compiler checks that your annotation is consistent with how the type actually uses T:

TypeScript in and out on type parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

If an annotation contradicts the structure, you get an error at the declaration itself. For example, interface Bad<out T> { accept: (value: T) => void } fails with error TS2636: Type 'Bad<sub-T>' is not assignable to type 'Bad<super-T>' as implied by variance annotation. The sub-T and super-T in the message stand for "some subtype of T" and "some supertype of T".

When should you write them? Rarely. They help in two situations: documenting intent on a widely used generic type in a library, and speeding up the compiler for very large, deeply recursive types where measuring variance is expensive. Note that methods written with method syntax (accept(value: T): void) are checked bivariantly for historical reasons, so the compiler can't catch a wrong annotation there; use property syntax (accept: (value: T) => void) when variance matters.

When type gymnastics hurt

Everything in this lesson is legitimate, and all of it can be overdone. Signs that a type has become a liability:

  • Error messages nobody can read. A typo in a call to a function typed with three nested conditional types can produce a 20-line error. If teammates can't understand the error, the type has failed at its main job.
  • Slow editors and builds. Deep recursion, huge unions and repeated instantiation of large mapped types make the compiler work hard. The native TypeScript 7 compiler is much faster, but complexity still scales badly. tsc --extendedDiagnostics prints how many types were instantiated if you need to measure it.
  • Assertions everywhere inside. If the implementation needs an as on every line to satisfy a fancy signature, the type isn't describing the code; it's fighting it.
  • Types nobody can change. A type that only its author understands becomes frozen, and people start working around it with any.

Some practical rules:

  1. Start with plain interfaces, unions and generics. Reach for conditional or recursive types only when a public API clearly benefits, such as typed event names, routes or paths.
  2. Name intermediate types (type Handlers<E> = ...) instead of nesting everything in one expression, and test them with Expect<Equal<...>> checks like the ones in this chapter.
  3. Prefer a small runtime check (a type guard) over a type that tries to model every possible string or number.
  4. Keep the clever part in one place. Callers should see simple signatures and simple errors.

A good test for any advanced type: write the error message a user would get for the most common mistake. If it's clear, keep the type. If it isn't, simplify the type or add an overload with a friendlier signature.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does DeepReadonly check for functions before checking for objects?

    Functions are objects. Mapping over their keys produces a plain object type without a call signature, so the function branch returns them unchanged.
  2. 2. What is the type of concat([1, 'two'], [true]) with the signature concat<A extends unknown[], B extends unknown[]>(a: [...A], b: [...B]): [...A, ...B]?

    The [...A] parameter form makes TypeScript infer tuples, and spreading them gives a three-element tuple. Literals widen to number, string and boolean because the elements are not const.
  3. 3. Given type UserId = string & { readonly [brand]: 'UserId' }, what is a UserId at runtime?

    The brand exists only in the type system. The value created with raw as UserId is the same string, with no extra property.
  4. 4. Does interface Box<out T> { set: (value: T) => void } compile?

    The compiler checks variance annotations against the structure. A function-typed property that takes T is contravariant in T, which contradicts out.
  5. 5. Which is the best sign that an advanced type should be simplified?

    Advanced features are fine when they make an API safer and clearer. Unreadable errors and assertion-heavy implementations mean the type costs more than it saves.

Summary

  • Recursive types like DeepReadonly, DeepPartial and Paths walk nested objects; order the branches carefully (functions, arrays, objects, primitives).
  • Paths<T> plus PathValue<T, P> type dotted-path APIs such as get(obj, 'a.b.c'), but large or recursive structures can explode.
  • Variadic tuple types ([...A, ...B]) type functions that concatenate or split argument lists; write parameters as [...A] to infer tuples.
  • Branded types (T & { readonly [brand]: Name }) stop structurally identical values from being mixed; create them through validating constructor functions.
  • out, in and in out declare variance on type parameters; the compiler checks them (TS2636). Use them rarely.
  • Type-level code is a tool for safer public APIs. If errors become unreadable or implementations fill up with assertions, simplify.

Next: Modules