Middle+
What other utility types in TypeScript do you know? Name the most popular ones.
sobes.tech AI
Answer from AI
TypeScript has many utility types that help work with types more flexibly and conveniently. Here are the most popular ones:
- 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.
- Record<K, T> — creates a type of object with keys from K and values of type 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 type T all 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 the parameter types of function T as a tuple.
Example of using Partial:
interface User {
id: number;
name: string;
age: number;
}
const updateUser = (user: Partial<User>) => {
// you can pass only some properties
}
updateUser({ name: "Alice" });
These utilities greatly simplify working with types and make the code more expressive.