Sobes.tech
Middle

Are you familiar with TypeScript? What are utility types, and can you give examples?

sobes.tech AI

Answer from AI

Utility types in TypeScript are built-in types that allow transforming or combining other types for convenience and code reduction.

Examples:

  • Partial<T> — makes all properties of type T optional.
  • Required<T> — makes all properties of type T mandatory.
  • Readonly<T> — makes all properties of type T read-only.
  • Pick<T, K> — selects only the properties with keys K from type T.
  • Omit<T, K> — excludes properties with keys K from type T.

Example:

type User = {
  id: number;
  name: string;
  age?: number;
};

// All properties are optional
const updateUser: Partial<User> = { name: "Alice" };

// Only id and name
type UserPreview = Pick<User, "id" | "name">;

// All properties are read-only
const readonlyUser: Readonly<User> = { id: 1, name: "Bob" };
Are you familiar with TypeScript? What are utility… - sobes.tech