Tell about utility types in TypeScript: which ones have you used and for what?
sobes.tech AI
Answer from AI
In TypeScript, utility types are built-in types that help transform or combine other types, simplifying work with types and increasing code readability.
Commonly used utility types:
-
Partial<T> — makes all properties of type T optional. Useful for updating objects when not all fields are required.
interface User { id: number; name: string; age: number; } const updateUser: Partial<User> = { name: "New Name" }; -
Required<T> — makes all properties required.
-
Readonly<T> — makes all properties read-only, preventing their modification.
-
Pick<T, K> — selects only the specified properties K from type T.
-
Omit<T, K> — excludes the specified properties K from type T.
-
Record<K, T> — creates a type for an object with keys K and values of type T.
-
Exclude<T, U> — excludes from type T all types that are present in U.
-
Extract<T, U> — keeps only the types in T that are also in U.
-
NonNullable<T> — excludes null and undefined from type T.
Using utility types helps write more expressive and safe code, avoiding duplication and errors when working with types.