TypeScriptInterview preparation
Intermediate·Concept·2 min read

What are generics and utility types?

Practice this question

Definition:

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.

  • Partial and Readonly are shallow type transformations; they do not recursively change every nested object or freeze runtime data.

Example:

TypeScript
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.
Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “What are generics and utility types?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.