Utility Types in TypeScript
Utility Types in TypeScript
Section titled “Utility Types in TypeScript”What are Utility Types?
Section titled “What are Utility Types?”Utility types are built-in generic types that transform existing types into new types. They save you from writing repetitive type transformations.
Partial
Section titled “Partial”interface User { name: string; age: number; email: string;}
// All properties become optionaltype PartialUser = Partial<User>;// { name?: string; age?: number; email?: string }
function updateUser(id: string, updates: Partial<User>): void { // Only updates provided fields}Required
Section titled “Required”interface Config { url?: string; timeout?: number;}
// All properties become requiredtype StrictConfig = Required<Config>;// { url: string; timeout: number }Readonly
Section titled “Readonly”type ImmutableUser = Readonly<User>;// { readonly name: string; readonly age: number; readonly email: string }Pick<T, K>
Section titled “Pick<T, K>”type UserName = Pick<User, "name" | "email">;// { name: string; email: string }Omit<T, K>
Section titled “Omit<T, K>”type UserWithoutEmail = Omit<User, "email">;// { name: string; age: number }Record<K, T>
Section titled “Record<K, T>”type PageInfo = { title: string; url: string;};
type Pages = Record<string, PageInfo>;// { [key: string]: { title: string; url: string } }ReturnType
Section titled “ReturnType”function createUser() { return { id: 1, name: "Alice" };}
type UserType = ReturnType<typeof createUser>;// { id: number; name: string }Parameters
Section titled “Parameters”function greet(name: string, age: number): void {}
type GreetParams = Parameters<typeof greet>;// [name: string, age: number]Real Project Example
Section titled “Real Project Example”// Form state managementinterface FormState { name: string; email: string; age: number; terms: boolean;}
type FormErrors = Partial<Record<keyof FormState, string>>;type FormTouched = Record<keyof FormState, boolean>;
// API response transformationtype ApiUser = { id: number; name: string; email: string; password_hash: string; created_at: string;};
type PublicUser = Omit<ApiUser, "password_hash">;type CreateUserPayload = Omit<ApiUser, "id" | "created_at">;Interview Questions
Section titled “Interview Questions”Easy: What does Partial<T> do?
Medium: What’s the difference between Pick and Omit?
Hard: How would you use ReturnType with complex functions?