Sub topic 12
Writing Your Own Utility Types
Assume you know interfaces, type aliases, unions, string literal types, and generic syntax. This chapter uses keyof, indexed access types, mapped types, and conditional types.
Built-in utility types are reusable type transformations. You can write a custom utility when your project needs a transformation that TypeScript does not provide directly. The safest approach is to start with a generic type and transform each property systematically.
The mapped-type pattern
A mapped type loops over the keys of another type. keyof T produces a union of the keys in T. For a property key K, T[K] means “the type of property K in T.”
interface User {
id: number;
name: string;
email?: string;
}
type MyPartial<T> = {
[K in keyof T]?: T[K];
};
type MyRequired<T> = {
[K in keyof T]-?: T[K];
};
type MyReadonly<T> = {
readonly [K in keyof T]: T[K];
};
type MyPick<T, K extends keyof T> = {
[P in K]: T[P];
};
type MyRecord<K extends PropertyKey, V> = {
[P in K]: V;
};
const draft: MyPartial<User> = { name: "Ada" };
const complete: MyRequired<User> = {
id: 1,
name: "Ada",
email: "[email protected]",
};
const preview: MyPick<User, "id" | "name"> = {
id: 1,
name: "Ada",
};
const labels: MyRecord<"home" | "settings", string> = {
home: "Home",
settings: "Settings",
};
console.log(draft, complete, preview, labels);The ? modifier makes each property optional. The -? modifier removes optionality. The readonly modifier prevents reassignment through that type. The extends keyof T constraint ensures that MyPick can only select real keys from T.
PropertyKey is the built-in type for valid object keys: strings, numbers, and symbols.
Building a recursive utility
Mapped types only transform the current level. A custom recursive utility can transform nested objects too.
type DeepPartial<T> = T extends object
? { [K in keyof T]?: DeepPartial<T[K]> }
: T;
interface Settings {
theme: {
color: string;
size: number;
};
notifications: {
email: boolean;
};
}
const settingsPatch: DeepPartial<Settings> = {
theme: {
color: "blue",
},
notifications: {},
};
console.log(settingsPatch);DeepPartial<Settings> makes theme and notifications optional. It also makes color, size, and email optional inside those nested objects.
The conditional type checks whether T is an object. If it is, the utility maps over its keys and calls itself for each property. Otherwise, it returns T unchanged. This keeps primitive values such as string, number, and boolean intact.
Custom transformations with conditional types
Conditional types can also distribute over a union. When a naked type parameter appears on the left side of extends, TypeScript evaluates each union member separately.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
type RemoveKind<T> = T extends unknown
? Omit<T, "kind">
: never;
type ShapeDetails = RemoveKind<Shape>;
// { radius: number } | { side: number }
const circle: ShapeDetails = { radius: 10 };
const square: ShapeDetails = { side: 5 };
console.log(circle, square);The conditional wrapper keeps the two union members separate. Without it, some transformations can lose member-specific properties.
Common mistakes
| Mistake | Result | Better approach |
|---|---|---|
| Using `string` instead of `keyof T` | Any string is accepted as a key | Constrain keys with `K extends keyof T` |
| Forgetting `T[K]` | Property values lose their original types | Index the source type |
| Expecting `Partial<T>` to recurse | Nested properties remain required | Write a recursive utility |
| Recursing into every object | Arrays and functions may transform unexpectedly | Add special cases when your project needs them |
Keep custom utilities small and give them names that describe their behavior. A utility that recursively transforms objects may need additional rules for arrays, tuples, dates, maps, and functions.
Exercise
Write a type named Nullable<T> that keeps every key in T but allows each property to also be null.
Show answer
type Nullable<T> = { [K in keyof T]: T[K] | null };