Typescript utility types are one of the most useful typing features in Typescript that you will see everywhere in open source projects and that you will definitely start using once I teach them to you today.
Without further ado, let’s dive straight into it.
Partial
Makes all the fields in the interface/type optional.
type Car {
id: string
name: string
}
Partial<Car>
// {
// id?: string | undefined
// name?: string | undefined
// }
Required
The opposite of Partial, it makes all the fields required (even the optional ones)
type Car {
id: string
name?: string
}
Required<Car>
// {
// id: string
// name: string
// }
Omit
Removes properties from a type/interface
type Car {
id?: string
name: string
weight: number
}
Omit<Car, "id" | "name">
// {
// weight: number
// }
Pick
Picks only the properties specified from the type/interface
type Car {
id?: string
name: string
weight: number
}
Pick<Car, "id" | "name">
// {
// id: string
// name: string
// }
Readonly
Makes all the properties readonly.
type Car {
id?: string
name: string
weight: number
}
Readonly<Person>
// {
// readonly id?: string
// readonly name: string
// readonly weight: number
// }
Awaited
Unwraps the return type of the promise
type StringPromise = Promise<string>
type Result = Awaited<StringPromise>
// Result type is string
ReturnType
Gets the return type of a function
type Func = (a: string) => number;
type ReturnValue = ReturnType<Func>
// ReturnType type is number
NonNullable
Removes null and undefined from union types
type MaybeString = string | null | undefined
type DefinitelyString = NonNullable<MaybeString>
// DefinitelyString type is string
Happy coding!
Mazen
My Youtube channel: @WebDevKit
My Github: @djzenma
My twitter: @djzenma
Top comments (0)