Utility types are built-in generic types that transform existing types, so you can derive new types instead of duplicating definitions. Base type for examples interface User { id: string; name: string; email: string; role: 'admin' | 'user'; createdAt: Date; } Partial<T> — all properties optional type UserUpdate = Partial<User>; function updateUser(id: string, changes: Partial<User>) { ... } updateUser('1', { name: 'Asha' }); // other fields not required Useful for PATCH requests, form drafts and default-merging functions. Required<T> — all properties required type CompleteSettings = Required<Settings>; Readonly<T> — properties cannot be reassigned const config: Readonly<User> = loadUser(); config.name = 'x'; // compile error Pick<T, K> — keep only selected properties type UserSummary = Pick<User, 'id' | 'name'>; Useful for list views and API responses. Omit<T, K> — remove selected properties type CreateUserRequest = Omit<User, 'id' | 'createdAt'>; Common for create requests where the server generates some fields. Record<K, T> — object type with keys K and values T type RolePermissions = Record<User['role'], string[]>; const permissions: RolePermissions = { admin: ['*'], user: ['read'] }; The compiler ensures every key exists. Other frequently used utility types - Exclude<T, U>: removes union members — Exclude<'a' | 'b' | 'c', 'a'> gives 'b' | 'c'. - Extract<T, U>: keeps matching union members. - NonNullable<T>: removes null and undefined. - ReturnType<F>: the return type of a function type — type Result = ReturnType<typeof createStore>. - Parameters<F>: tuple of a function's parameter types. - Awaited<T>: the resolved type of a promise — Awaited<ReturnType<typeof fetchUser>>. - InstanceType<C>: instance type of a class constructor. - NoInfer<T> (TypeScript 5.4+): prevents a type parameter from being inferred from a particular argument. Combining utility types type UserPatch = Partial<Omit<User, 'id' | 'createdAt'>>; type PublicUser = Readonly<Pick<User, 'id' | 'name'>>; How they work (mapped types) Utility types are built with mapped and conditional types, for example: type MyPartial<T> = { [K in keyof T]?: T[K] }; type MyReadonly<T> = { readonly [K in keyof T]: T[K] }; type MyPick<T, K extends keyof T> = { [P in K]: T[P] }; Understanding this lets you write your own: type Nullable<T> = { [K in keyof T]: T[K] | null }; Caveats - Partial and Readonly are shallow: nested objects are not made optional or read-only (write a DeepPartial type if needed). - Omit does not check that the omitted keys exist (Omit<User, 'typo'> compiles); some teams use a stricter custom version. - Types are compile-time only; they do not validate runtime data. Interview summary: "Utility types derive new types from existing ones: Partial makes fields optional, Pick and Omit select or remove fields, Record builds typed key-value maps, and others like ReturnType, Exclude and NonNullable help compose types without duplication."
Ravindra Wadile · · 0 likes