DEV Community

Mazen
Mazen

Posted on

Typescript utility types: unleashing the power of TS generics

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
// }

Enter fullscreen mode Exit fullscreen mode

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
// }
Enter fullscreen mode Exit fullscreen mode

Omit

Removes properties from a type/interface

type Car {
  id?: string
  name: string
  weight: number
}
Omit<Car, "id" | "name"> 
// {
//   weight: number
// }
Enter fullscreen mode Exit fullscreen mode

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
// }
Enter fullscreen mode Exit fullscreen mode

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
// }
Enter fullscreen mode Exit fullscreen mode

Awaited

Unwraps the return type of the promise

type StringPromise = Promise<string>
type Result = Awaited<StringPromise> 
// Result type is string
Enter fullscreen mode Exit fullscreen mode

ReturnType

Gets the return type of a function

type Func = (a: string) => number;
type ReturnValue = ReturnType<Func>
// ReturnType type is number
Enter fullscreen mode Exit fullscreen mode

NonNullable

Removes null and undefined from union types

type MaybeString = string | null | undefined
type DefinitelyString = NonNullable<MaybeString>
// DefinitelyString type is string
Enter fullscreen mode Exit fullscreen mode

Happy coding!
Mazen
My Youtube channel: @WebDevKit
My Github: @djzenma
My twitter: @djzenma

Top comments (1)

Collapse
 
kristiyan_velkov profile image
Kristiyan Velkov

Take your TypeScript skills to new heights with "Mastering TypeScript Core Utility Types":

๐Ÿ“– Buy on Leanpub
๐Ÿ“– Buy on Amazon