What are generics and utility types?
Try code in the playgroundUnderstand the concept
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.
Important ideas
-
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.
Work through the 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.
Can you explain it without the notes?
What are generics and utility types?
Use your own words. Explain an example and one limitation before checking the explanation.
Check your explanation
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.
Turn this concept into a clear answer.
- A useful generic connects types; adding a generic that has no meaningful relationship often adds noise.
Keep connecting the ideas.
Next lesson: What are union, intersection, keyof and typeof?Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “What are generics and utility types?”. Examples are study fragments; framework behavior can depend on your version.