Middle
Tell us about utility types in TypeScript.
sobes.tech AI
Answer from AI
Utility types in TypeScript are built-in helper types that simplify common operations on types, such as transformations, extractions, or exclusions of certain properties. They enhance the flexibility and readability of code.
Main useful types:
Partial<Type>: Creates a type where all properties ofTypeare optional.// Creates a type with optional properties 'name' and 'age' type PartialUser = Partial<{ name: string; age: number }>;Readonly<Type>: Creates a type where all properties ofTypeare read-only.// Creates a type with properties 'name' and 'age' that are read-only type ReadonlyUser = Readonly<{ name: string; age: number }>;Pick<Type, Keys>: Creates a type by selecting a set of propertiesKeysfromType.Keyscan be a string literal or a union of string literals.// Creates a type containing only the 'name' property type UserWithName = Pick<{ name: string; age: number }, 'name'>;Omit<Type, Keys>: Creates a type by excluding a set of propertiesKeysfromType.// Creates a type containing only the 'age' property type UserWithoutName = Omit<{ name: string; age: number }, 'name'>;Exclude<UnionType, ExcludedMembers>: Creates a type by excluding all members ofUnionTypethat are assignable toExcludedMembers.// Creates a type excluding 'null' from the union type NonNullableString = Exclude<string | null | undefined, null | undefined>;Extract<Type, Union>: Extracts fromTypeall members that are assignable toUnion.// Extracts 'null' and 'undefined' from the union type JustNullOrUndefined = Extract<string | null | undefined, null | undefined>;NonNull<Type>: ExcludesnullandundefinedfromType.// Creates a type excluding 'null' and 'undefined' type NonNullStringOrNumber = NonNullable<string | number | null | undefined>;Parameters<Type>: Gets the parameter types of functionTypeas a tuple.// Gets the parameter types of a function: [string, number] type FuncParams = Parameters<(a: string, b: number) => void>;ReturnType<Type>: Gets the return type of functionType.// Gets the return type of a function: number type FuncReturn = ReturnType<() => number>;ConstructorParameters<Type>: Extracts the parameter types of a constructor type.// Gets the parameter types of a class constructor: [string, number] type MyClassParams = ConstructorParameters<typeof MyClass>; class MyClass { constructor(name: string, age: number) {} }InstanceType<Type>: Extracts the instance type of a constructor type.// Extracts the instance type of a class: MyClass type MyClassInstance = InstanceType<typeof MyClass>; class MyClass { constructor(name: string, age: number) {} }
Using utility types helps create more type-safe, flexible, and maintainable code.