Sobes.tech
Middle

How often have you had to work with generics? Where have you used utility types: Pick, Omit, Partial, Record, ReturnType, Exclude?

sobes.tech AI

Answer from AI

Generics and utility types in TypeScript allow creating flexible and reusable types, significantly improving code quality and safety.

Experience with usage:

  • I often use generics when writing React components to type props with different data types.
  • I use utility types to transform types without duplicating code.

Examples of utility types usage:

  • Pick<T, K> — selects only properties K from type T. For example, to create a type with part of the interface's fields.
  • Omit<T, K> — excludes properties K from type T.
  • Partial<T> — makes all properties of type T optional, convenient for updating objects.
  • Record<K, T> — creates an object with keys K and values of type T, useful for mapping.
  • ReturnType<T> — extracts the return type of function T.
  • Exclude<T, U> — excludes from type T all types compatible with U.

Example:

interface User {
  id: number;
  name: string;
  email: string;
}

// Create a type with only id and name
 type UserPreview = Pick<User, 'id' | 'name'>;

// Type with optional fields for updating
 type UserUpdate = Partial<User>;

// Function returning User
function getUser(): User {
  return { id: 1, name: 'Alice', email: 'alice@example.com' };
}

// Type of the function's return value
 type UserType = ReturnType<typeof getUser>;