Sub topic 3
Recursive Mapped Types and Type-Level Recursion
Assume you know generics, unions, tuples, mapped types, function signatures, and basic template literal types. These utilities run entirely in the TypeScript type checker; they do not create JavaScript at runtime.
Building `DeepReadonly`
A recursive mapped type applies a transformation to each property, then applies itself to nested property types. The base cases return functions and primitive values unchanged.
type DeepReadonly<T> =
T extends (...args: any[]) => unknown ? T :
T extends readonly unknown[]
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T extends object
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T;
type Config = {
server: { host: string; ports: number[] };
log: () => void;
};
type FrozenConfig = DeepReadonly<Config>;
// FrozenConfig.server.host is readonly.
// FrozenConfig.server.ports is readonly.
// FrozenConfig.log keeps its function type.The object branch is recursive. Without the primitive and function branches, the utility could transform values that should remain unchanged.
Parsing Strings with `infer`
Template literal patterns can capture string fragments. This splitter consumes one delimiter at a time and recurses on the remainder.
type Split<S extends string, D extends string> =
S extends `${infer Head}${D}${infer Tail}`
? [Head, ...Split<Tail, D>]
: [S];
type Parts = Split<"a.b.c", ".">; // ["a", "b", "c"]Reversing Tuples with an Accumulator
Variadic tuple spreads let a conditional type remove the first element. An accumulator stores the result built so far.
type Reverse<
T extends unknown[],
Acc extends unknown[] = []
> = T extends [infer Head, ...infer Rest]
? Reverse<Rest, [Head, ...Acc]>
: Acc;
type Result = Reverse<[1, 2, 3]>; // [3, 2, 1]Termination and Compiler Limits
Every recursive utility needs a base case. Split stops when no delimiter remains. Reverse stops when the tuple is empty. A utility without a reachable base case can produce an excessively deep instantiation error.
Tail-recursive designs pass accumulated work as a type parameter and make the recursive call the final operation. They often handle larger inputs, but TypeScript still imposes recursion and instantiation limits.
Testing Type Utilities
Use compile-time assertions to verify results without running code.
type Equal<X, Y> =
(<T>() => T extends X ? 1 : 2) extends
(<T>() => T extends Y ? 1 : 2) ? true : false;
type Expect<T extends true> = T;
type TestReverse =
Expect<Equal<Reverse<[1, 2, 3]>, [3, 2, 1]>>;
type TestSplit =
Expect<Equal<Split<"a.b.c", ".">, ["a", "b", "c"]>>;Exercise
What happens if the base case is removed from Reverse?
Show answer
The type keeps recursing until TypeScript reports an excessively deep type instantiation error.