DEV Community

Cover image for 10 Typescript utilities you need to know 🔥
hichem ben chaabene
hichem ben chaabene

Posted on • Updated on

10 Typescript utilities you need to know 🔥

In this article, i'm going to cover 10 typescript utilities every developer should know.

  • Partial type
  • Required type
  • Readonly
  • Pick
  • Omit
  • Record
  • Exclude
  • Extract
  • NonNullable
  • Return type

1- Partial type

Type Person = {
  name: string;
  age: number;
  gender: string;
  address: string;
}
// Partial<T> type Partial sets all properties 
// of Person to optional
type PartialPerson = Partial<Person>;
Enter fullscreen mode Exit fullscreen mode

2-Required

// Required<T> all properties of `RequiredPerson` 
// are required
type RequiredPerson = Required<Person>;
Enter fullscreen mode Exit fullscreen mode

3-Readonly

// Readonly<T>: Creates a type with all properties
// of T set to readonly.
type ReadonlyPerson = Readonly<Person>;
Enter fullscreen mode Exit fullscreen mode

4-Pick

// Creates a type by picking only the specified
// properties K from T.
type PersonName = Pick<Person, 'name'>;
Enter fullscreen mode Exit fullscreen mode

5-Omit

// Omit<T,K> Creates a type by omitting the specified
// properties K from T.
type PersonWithoutAge = Omit<Person, 'age'>;
Enter fullscreen mode Exit fullscreen mode

6-Record

// Record<K,T> Creates a type with keys of type 
// K and values of type T.
type StringRecord = Record<string, Person>;
Enter fullscreen mode Exit fullscreen mode

7-Exclude

// Exclude<T, U>: Creates a type by excluding all types
// from T that are assignable to U.
type NumbersOnly = Exclude<number | string, string>;
Enter fullscreen mode Exit fullscreen mode

8-Extract

// Extract<T, U> Creates a type by extracting all types
// from T that are assignable to U.
type StringOnly = Extract<number | string, string>;
Enter fullscreen mode Exit fullscreen mode

9-NonNullable

// NonNullable<T>: Creates a type by removing null and undefined from T.
type NonNullString = NonNullable<string | null | undefined>;
Enter fullscreen mode Exit fullscreen mode

10-ReturnType

// ReturnType<T>: Obtains the return type of a function type.
type MyFunctionReturnType = ReturnType<MyFunction>;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)