Sobes.tech
Middle+

Какие utility-типы в TypeScript знаешь?

sobes.tech AI

Answer from AI

In TypeScript, there are several useful utility types that help transform and combine types:

  • Partial<T> — makes all properties of type T optional.
  • Required<T> — makes all properties of type T required.
  • Readonly<T> — makes all properties of type T read-only.
  • Record<K, T> — creates a type of object with keys K and values T.
  • Pick<T, K> — selects a subset of properties K from type T.
  • Omit<T, K> — excludes properties K from type T.
  • Exclude<T, U> — excludes from type T all types compatible with U.
  • Extract<T, U> — selects from T only those types compatible with U.
  • NonNullable<T> — excludes null and undefined from type T.
  • ReturnType<T> — gets the return type of function T.
  • Parameters<T> — gets a tuple of parameter types of function T.

Example of using Partial:

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

const updateUser = (user: Partial<User>) => {
  // can pass only some fields
};

updateUser({ name: "Alice" });

These types help write more expressive and safer code.