TypeScript Utility Types - Partial, Required, Readonly, Pick, Omit, Record, Exclude, Extract & More
Master TypeScript built-in utility types: Partial, Required, Readonly, Pick, Omit, Record, Exclude, Extract, and more!
Introduction
TypeScript has built-in utility types for common type transformations! Let's master them!
What You Will Learn
- All major TypeScript utility types
- Practical examples
- Best practices
Prerequisites
1. Partial<T>
Makes all properties of T optional!
interface User {
id: number;
name: string;
email: string;
}
type PartialUser = Partial<User>;
// { id?: number; name?: string; email?: string }
2. Required<T>
Makes all properties of T required!
type RequiredUser = Required<PartialUser>;
// { id: number; name: string; email: string }
3. Readonly<T>
Makes all properties readonly!
type ReadonlyUser = Readonly<User>;
4. Pick<T, Keys>
Picks set of properties Keys from T!
type UserNameEmail = Pick<User, "name" | "email">;
// { name: string; email: string }
5. Omit<T, Keys>
Removes set of properties Keys from T!
type UserWithoutId = Omit<User, "id">;
// { name: string; email: string }
6. Record<Keys, T>
Constructs an object with keys Keys of type T!
type PhoneBook = Record<string, string>;
// { [key: string]: string }
7. Exclude<Union, Excluded>
Excludes types from a union!
type Status = "pending" | "approved" | "rejected";
type FinalStatus = Exclude<Status, "pending">;
// "approved" | "rejected"
8. Extract<Union, Extracted>
Extracts types from a union!
type Status = "pending" | "approved" | "rejected";
type ActiveStatus = Extract<Status, "approved">;
// "approved"
Best Practices
- Use utility types: Don't reinvent the wheel!
- Combine them:
Partial<Pick<User, "name">>!
Summary
Utility types save you time and make type transformations easy!
Related Articles
Previous Tutorial
← Generics
Next Tutorial
Let's learn React with TypeScript! → React with TypeScript