Build Reusable Utility Types with Generics
How to create reusable TypeScript utility types using conditional types, mapped types, template literals, and generic constraints for type-safe APIs.
Overview
TypeScript can compute types from other types. Conditional types pick between two shapes, mapped types walk every property of an object, and template literal types assemble new string types. Generics tie it all together, which is how built-ins like Partial<T> or Pick<T, K> work. Writing your own utilities stops you from repeating the same type shapes across an API surface, and pushes mistakes into the compiler instead of code review.
When to Use
- Deriving form types from API response types (omit server-only fields)
- Making specific properties required or optional based on context
- Creating type-safe builders that enforce property assignment order
- Extracting function parameter or return types for reuse
- Building API client types from schema definitions
Reach for them alongside exhaustive discriminated unions: unions describe the variants, utility types reshape them. And almost every React Hook Form setup ends up with a form type that’s a slimmed-down API model, which is exactly what these types are for.
When NOT to Use
- Simple applications with few types: built-in utilities (
Partial,Pick,Omit) are enough - When a plain type alias reads better: a custom utility type only pays off if it gets reused
- Anything checked at runtime: utility types disappear at compile time, so use Zod for those checks
Solution
Make specific properties required
type RequireFields<T, K extends keyof T> = T & {
[P in K]-?: T[P];
};
interface User {
id?: string;
name?: string;
email?: string;
role: string;
}
type UserWithRequiredEmail = RequireFields<User, "id" | "email">;
// { id: string; name?: string; email: string; role: string }
Make specific properties optional
type OptionalFields<T, K extends keyof T> = Omit<T, K> & {
[P in K]?: T[P];
};
interface CreateUserDTO {
name: string;
email: string;
role: string;
avatar: string;
}
type UpdateUserDTO = OptionalFields<CreateUserDTO, "name" | "email" | "role" | "avatar">;
// All fields optional: equivalent to Partial<CreateUserDTO>
Pick properties by value type
type PickByValue<T, ValueType> = {
[P in keyof T as T[P] extends ValueType ? P : never]: T[P];
};
interface Config {
port: number;
host: string;
debug: boolean;
retries: number;
logFile: string;
}
type StringConfig = PickByValue<Config, string>;
// { host: string; logFile: string }
type NumberConfig = PickByValue<Config, number>;
// { port: number; retries: number }
Omit properties by value type
type OmitByValue<T, ValueType> = {
[P in keyof T as T[P] extends ValueType ? never : P]: T[P];
};
type NonBooleanConfig = OmitByValue<Config, boolean>;
// { port: number; host: string; retries: number; logFile: string }
Deep partial
type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};
interface AppConfig {
server: {
port: number;
host: string;
};
database: {
url: string;
poolSize: number;
};
logging: {
level: string;
file: string;
};
}
type PartialConfig = DeepPartial<AppConfig>;
// All properties optional at all levels
const config: PartialConfig = {
server: { port: 3000 }, // host is optional
};
Deep readonly
type DeepReadonly<T> = {
readonly [P in keyof T]: T[P] extends object ? DeepReadonly<T[P]> : T[P];
};
type ReadonlyConfig = DeepReadonly<AppConfig>;
// All properties readonly at all levels
Template literal types
type EventName<T extends string> = `on${Capitalize<T>}`;
type ClickEvent = EventName<"click">; // "onClick"
type FocusEvent = EventName<"focus">; // "onFocus"
type EventHandler<T extends string> = {
[K in EventName<T>]?: (event: { type: T; target: HTMLElement }) => void;
};
type ButtonHandlers = EventHandler<"click" | "focus" | "blur">;
// { onClick?: ...; onFocus?: ...; onBlur?: ... }
API response wrapper
type ApiResponse<T, E = string> =
| { success: true; data: T; timestamp: number }
| { success: false; error: E; timestamp: number };
type UserResponse = ApiResponse<{ id: string; name: string }>;
type ListResponse<T> = ApiResponse<T[], "not_found" | "server_error">;
Builder pattern with type safety
type Builder<T> = {
[K in keyof T]: (value: T[K]) => Builder<Omit<T, K>>;
} & { build: () => T };
function createBuilder<T>(): Builder<T> {
const state = {} as T;
const proxy = {} as Builder<T>;
for (const key in state) {
proxy[key] = ((value: any) => {
(state as any)[key] = value;
return proxy;
}) as any;
}
proxy.build = () => state;
return proxy;
}
interface User {
id: string;
name: string;
email: string;
}
const user = createBuilder<User>()
.id("123")
.name("Alice")
.email("alice@example.com")
.build();
Extract route parameters
type RouteParams<T extends string> = T extends `${string}:${infer Param}/${infer Rest}`
? { [K in Param]: string } & RouteParams<Rest>
: T extends `${string}:${infer Param}`
? { [K in Param]: string }
: {};
type UserRoute = "/users/:userId/posts/:postId";
type UserRouteParams = RouteParams<UserRoute>;
// { userId: string; postId: string }
function navigate<T extends string>(
route: T,
params: RouteParams<T>
): string {
let path = route;
for (const [key, value] of Object.entries(params)) {
path = path.replace(`:${key}`, value as string);
}
return path;
}
navigate("/users/:userId/posts/:postId", { userId: "123", postId: "456" });
// "/users/123/posts/456"
Mutable version of a type
type Mutable<T> = {
-readonly [P in keyof T]: T[P];
};
interface ReadonlyUser {
readonly id: string;
readonly name: string;
readonly email: string;
}
type EditableUser = Mutable<ReadonlyUser>;
// { id: string; name: string; email: string }: no readonly
Function parameter and return types
type FirstParam<T> = T extends (first: infer P, ...rest: any[]) => any ? P : never;
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
type AllParams<T> = T extends (...args: infer P) => any ? P : never;
function createUser(name: string, age: number, email: string): { id: string } {
return { id: "1" };
}
type Name = FirstParam<typeof createUser>; // string
type Result = ReturnType<typeof createUser>; // { id: string }
type Params = AllParams<typeof createUser>; // [string, number, string]
Variants
The built-ins only go so far. These three patterns are the ones I keep reaching for.
Using with Zod for schema-derived types
import { z } from "zod";
const UserSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string().email(),
role: z.enum(["admin", "user", "guest"]),
});
type User = z.infer<typeof UserSchema>;
type CreateUserInput = OptionalFields<Omit<User, "id">, "role">;
// { name: string; email: string; role?: "admin" | "user" | "guest" }
type AdminUser = RequireFields<User, "role"> & { role: "admin" };
Conditional type with infer for array element
type ArrayElement<T> = T extends (infer E)[] ? E : never;
type StringElement = ArrayElement<string[]>; // string
type NumberElement = ArrayElement<number[]>; // number
type NotArray = ArrayElement<string>; // never
Promise unwrapping
type Awaited<T> = T extends Promise<infer U> ? U : T;
type Result = Awaited<Promise<string>>; // string
type Nested = Awaited<Promise<Promise<number>>>; // number (in TypeScript 4.5+)
Best Practices
- The advanced types guide goes deeper into each of these techniques.
Naming is half the battle. RequireFields<T, K> tells the next reader what it does; the raw T & { [P in K]-?: T[P] } pasted into every signature does not.
Constrain generics early. K extends keyof T turns a typo in a property name into a compile error instead of a silent never.
Compose instead of building monoliths. Omit<User, "id"> combined with RequireFields is easier to reason about than a fifty-line mapped type that does everything at once.
Check the result with a type assertion, not just that the file compiles:
type Test = RequireFields<User, "email">;
const ok: Test = { id: "1", email: "a@b.com", role: "user" };
And stick with the built-ins when they fit: Partial, Required, Pick, Omit and Readonly cover most everyday needs.
Common Mistakes
- Building a fifty-line utility type where a five-line alias would do. If nobody can read it, it isn’t helping.
- Trusting that “it compiles” means “it’s right”. A mapped type can compile and still produce the wrong shape, so verify it with a type assertion.
- Letting
neverslip through. A conditional type that doesn’t match resolves tonever, which then infects every mapped type built on top of it. - Forgetting the
-?modifier. Without it, properties stay optional even when you meant to make them required. - Skipping the
extends keyof Tconstraint. Skip it and TypeScript won’t complain about a misspelled key until the utility gets used somewhere far away.
Frequently Asked Questions
What is a conditional type?
It's T extends U ? X : Y: when T extends U you get X, otherwise Y. Add infer and it can also pull types out of whatever it's matching on.
What is a mapped type?
A type that walks every property of an existing type and rewrites it: { [P in keyof T]: NewType }. The + and - prefixes add or strip readonly and ? as you go.
Can utility types be used with enums?
They work, though a union of string literals usually reads better. keyof typeof MyEnum hands you the enum's keys as a union.
How do I debug a utility type?
Use type assertions to check the result:
type Test = RequireFields<User, "email">;
const test: Test = { id: "1", email: "a@b.com", role: "user" }; // Should compile
What is the difference between keyof T and keyof T & string?
keyof T can come back as string | number | symbol when T has non-string keys. Intersecting it with string keeps only the string ones, which is what template literal types want.
Related Resources
Exhaustive Type Checking with Discriminated Unions
How to use TypeScript discriminated unions for exhaustive type checking, ensuring all cases are handled at compile time with never type assertions.
RecipeForm Validation with react-hook-form and Zod
Build type-safe forms in React using react-hook-form with Zod schema validation, including nested fields, async rules, dynamic fields, and UI library integration.
RecipeReact useMemo and useCallback: When to Use Them
Learn when useMemo and useCallback help React rendering, when they add work, and what React Compiler changes about manual memoization.
GuideTypeScript Advanced Types: The Complete Guide
TypeScript advanced types in depth: conditional types, infer, mapped types, template literals, satisfies, variance, narrowing, and tested real-world patterns.