TypeScript2 min read
5 TypeScript Utility Types You Should Know
Built-in type transformations that save hours of work
S
Shahar Amir
5 TypeScript Utility Types You Should Know
TypeScript has built-in utility types that transform existing types. Here are the essential ones.
1. Partial
Makes all properties optional:
typescript
123456789101112131415
interface User { id: number; name: string; email: string;}
// All properties optionaltype UpdateUser = Partial<User>;
function updateUser(id: number, updates: Partial<User>) { // Can pass any subset of User properties}
updateUser(1, { name: "John" }); // ✅updateUser(1, { email: "new@email.com" }); // ✅2. Required
Makes all properties required (opposite of Partial):
typescript
123456789101112131415
interface Config { host?: string; port?: number; ssl?: boolean;}
// All properties now requiredtype StrictConfig = Required<Config>;
const config: StrictConfig = { host: "localhost", port: 3000, ssl: true, // Missing any = error!};3. Pick
Select specific properties:
typescript
123456789101112
interface User { id: number; name: string; email: string; password: string; createdAt: Date;}
// Only id and nametype UserPreview = Pick<User, "id" | "name">;
// { id: number; name: string; }4. Omit
Remove specific properties:
typescript
1234567891011
interface User { id: number; name: string; email: string; password: string;}
// Everything except passwordtype SafeUser = Omit<User, "password">;
// { id: number; name: string; email: string; }5. Record
Create object type with specific keys and value type:
typescript
123456789101112131415
type Status = "pending" | "active" | "done";
// Object with Status keys, number valuesconst taskCount: Record<Status, number> = { pending: 5, active: 3, done: 12,};
// Dynamic key mappingtype UserRoles = Record<string, string[]>;const roles: UserRoles = { admin: ["read", "write", "delete"], user: ["read"],};Bonus: Combining Them
typescript
12345678910111213141516
interface User { id: number; name: string; email: string; password: string; role: "admin" | "user";}
// Updatable fields (no id, partial)type UserUpdate = Partial<Omit<User, "id">>;
// Public user datatype PublicUser = Omit<User, "password" | "email">;
// Form data with required nametype UserForm = Partial<User> & Required<Pick<User, "name">>;Cheat Sheet
| Type | What it does |
|---|---|
| `Partial | All optional |
| `Required | All required |
| `Pick | Only these keys |
| `Omit | Everything except |
| `Record | Object with K keys |
#types#utility#generics
Stay Updated 📬
Get the latest tips and tutorials delivered to your inbox. No spam, unsubscribe anytime.