TypeScript includes powerful built-in Utility Types that facilitate global type transformations. Mastering these types enables engineers to write DRY, robust type definitions.
Core Built-in Utility Types
- •
Partial<T>: Makes all properties optional. - •
Required<T>: Makes all properties required. - •
Readonly<T>: Makes all properties immutable. - •
Record<K, T>: Constructs an object type with key typeKand value typeT. - •
Pick<T, K>: Constructs a type by picking specific propertiesKfromT. - •
Omit<T, K>: Constructs a type by removing propertiesKfromT. - •
Exclude<T, U>: Removes union members that are assignable toU. - •
ReturnType<T>: Extracts the return type of a function type.
interface UserProfile {
id: string;
username: string;
email: string;
bio?: string;
}
// Pick only public fields
type PublicUser = Pick<UserProfile, "id" | "username">;
// Omit sensitive email field
type SafeUser = Omit<UserProfile, "email">;
// Make profile fields optional for update operations
type UpdateUserProfileInput = Partial<Omit<UserProfile, "id">>;type PublicStatus = "active" | "invited" | "suspended";
type VisibleStatus = Exclude<PublicStatus, "suspended">;
async function loadUser(id: string) {
const response = await fetch(`/users/${id}`);
return response.json() as Promise<UserProfile>;
}
type UserLoaderResult = ReturnType<typeof loadUser>;Custom Mapped Types (Interview Question)
Implement custom MyOmit<T, K> without using the built-in Omit:
type MyOmit<T, K extends keyof T> = {
[P in keyof T as P extends K ? never : P]: T[P];
};Practice TypeScript Coding Live
Conduct Live Coding Interviews in the Browser
No candidate sign-up required. Create a room, share the link, and code together in real time with shared code execution.