Utility Types
TypeScript Utility Types
TypeScript ships a set of built-in generic types that transform existing types, reducing boilerplate.
Common utility types:
Partial<T>– makes every property of T optional.Required<T>– makes every property of T required (opposite of Partial).Readonly<T>– makes every property of T readonly.Pick<T, K>– constructs a type with only the properties K from T.Omit<T, K>– constructs a type with all properties of T except those in K.Record<K, V>– constructs an object type with keys of type K and values of type V.ReturnType<F>– extracts the return type of a function type F.
These types are built with conditional types and mapped types under the hood. You can compose them:
ts
type ReadonlyPartial<T> = Readonly<Partial<T>>;Code Examples
Partial, Required, Readonlytypescript
interface Config {
host: string;
port: number;
debug?: boolean;
}
function applyDefaults(partial: Partial<Config>): Config {
return { host: "localhost", port: 3000, ...partial };
}
const cfg = applyDefaults({ port: 8080 });
console.log(cfg.host, cfg.port);
const locked: Readonly<Config> = { host: "prod.example.com", port: 443 };
console.log(locked.host);Partial<Config> is useful for update/patch operations. Readonly<T> prevents accidental mutation.
Pick, Omit, Record, ReturnTypetypescript
interface User {
id: number;
name: string;
email: string;
password: string;
}
type PublicUser = Omit<User, "password">;
type UserSummary = Pick<User, "id" | "name">;
type UserMap = Record<number, PublicUser>;
function getUser(): User {
return { id: 1, name: "Alice", email: "alice@example.com", password: "secret" };
}
type GetUserReturn = ReturnType<typeof getUser>;
const summary: UserSummary = { id: 1, name: "Alice" };
const userMap: UserMap = { 1: { id: 1, name: "Alice", email: "alice@example.com" } };
console.log(summary);
console.log(userMap[1].email);Omit removes sensitive fields from a type. Record builds a typed map. ReturnType infers the return type without re-specifying it.
Quick Quiz
1. What does `Omit<User, 'password'>` produce?
2. Which utility type makes all properties optional?
Was this lesson helpful?