Utility Types
Partial, Required, Readonly, Pick, Omit, Record, ReturnType — TypeScript's built-in type transformers
Skills taught: ts.Partial, ts.Required, ts.Readonly, ts.Pick, ts.Omit, ts.Record, ts.ReturnType, ts.Parameters
Transforming existing types
interface User {
id: number;
name: string;
email: string;
role: 'admin' | 'user';
createdAt: string;
}
// Partial<T> — all fields become optional (useful for updates)
type UserUpdate = Partial<User>;
const update: UserUpdate = { name: 'New Name' }; // only name changed
// Required<T> — all optional fields become required
interface Config { host?: string; port?: number; }
type StrictConfig = Required<Config>;
const cfg: StrictConfig = { host: 'localhost', port: 3000 }; // both required
// Readonly<T> — all fields immutable
type FrozenUser = Readonly<User>;
const frozen: FrozenUser = { id: 1, name: 'Alice', email: 'a@b.com', role: 'user', createdAt: '2024' };
// frozen.name = 'Bob'; // Error: readonly
// Pick<T, K> — keep only certain fields
type UserSummary = Pick<User, 'id' | 'name' | 'role'>;
const summary: UserSummary = { id: 1, name: 'Alice', role: 'user' };
// Omit<T, K> — remove certain fields
type PublicUser = Omit<User, 'createdAt'>;
const pub: PublicUser = { id: 1, name: 'Alice', email: 'a@b.com', role: 'user' };
console.log(summary);
console.log(pub);
Record, ReturnType, and Parameters
// Record<K, V> — typed object/map
type RolePermissions = Record<'admin' | 'user' | 'guest', string[]>;
const permissions: RolePermissions = {
admin: ['read', 'write', 'delete'],
user: ['read', 'write'],
guest: ['read'],
};
// Record with string keys
type ScoreBoard = Record<string, number>;
const scores: ScoreBoard = { Alice: 95, Bob: 87, Charlie: 72 };
console.log(scores['Alice']);
// ReturnType<typeof fn> — extract return type
function getUser() {
return { id: 1, name: 'Alice', email: 'alice@example.com' };
}
type UserData = ReturnType<typeof getUser>; // { id: number; name: string; email: string; }
// Parameters<typeof fn> — extract parameter types as tuple
function login(username: string, password: string, remember: boolean): boolean {
return true;
}
type LoginParams = Parameters<typeof login>; // [string, string, boolean]
const args: LoginParams = ['alice', 'secret', true];
login(...args);
// NonNullable<T> — remove null and undefined
type MaybeName = string | null | undefined;
type Name = NonNullable<MaybeName>; // string
// Awaited<T> — unwrap Promise
type AwaitedUser = Awaited<Promise<{ id: number; name: string }>>;
// same as { id: number; name: string }
console.log(permissions);
Frequently Asked Questions
Is there a built-in DeepPartial utility type?
No, but it's commonly implemented: type DeepPartial<T> = T extends object ? { [K in keyof T]?: DeepPartial<T[K]> } : T. TypeScript doesn't include it because recursive mapped types have some edge cases. Libraries like 'utility-types' or 'ts-essentials' provide DeepPartial and other recursive variants.