What are generics and utility types?
Practice this questionDefinition:
Generics let a function, class or type work with different types while preserving relationships between inputs and outputs. Utility types transform existing types so the same fields do not need to be manually repeated. This reduces duplication without throwing away type information through any.
Key points:
-
Generics keep types connected:
function identity<T>(value: T): T. -
Partial<T>makes fields optional;Pick<T, K>selects fields. -
Omit<T, K>removes fields;Readonly<T>prevents assignment through that type. -
A generic constraint such as
T extends { id: number }requires a capability while preserving the rest of T. -
PartialandReadonlyare shallow type transformations; they do not recursively change every nested object or freeze runtime data.
Example:
function first<T>(items: T[]): T | undefined {
return items[0];
}
const name = first(['Asha', 'Ravi']); // string | undefined
type User = { id: number; name: string; email: string };
type UserPreview = Pick<User, 'id' | 'name'>;- The generic preserves the element type, and the return type includes the empty-array case.
Interview point:
- A useful generic connects types; adding a generic that has no meaningful relationship often adds noise.