DEV Community

Mazen
Mazen

Posted on

1

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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (1)

Collapse
 
kristiyanvelkov profile image
Kristiyan Velkov

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

📖 Buy on Leanpub
📖 Buy on Amazon

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay