Copy of Upload image to s3.png

Mapped types are one of the best tools in TypeScript for transforming types. It takes a type and turns it into another type in an organized and deliberate way. You can think of the mapped type as Array.map – iterating over it to create new types. This is the same pattern used to create utilities in TypeScript, such as Pick Partial, and Required. We will see examples of how to create your own Pick, Omit … with custom conditions.

Mapped types Syntax

[P in K]: T

Here, P is a variable that represents a property key of the original type K. We can customize P as we want; we can use it as is or create literal strings. T is the type that the property will be transformed into. Here, we can use it to create a new type.

Create mapped type

Let’s imagine we have a static union

type union = 'firstname' | 'lastname'

or we can create a union from an object we have already, using keyof and typeof

const obj  ={
 firstname:'wassim',
 lastname:'nassour'
}

type keys = keyof typeof obj

Let’s create a mapped type that switches all strings in the obj to a boolean

const obj ={ 
  firstname:string,
  lastname:string
}

type objBolean = {
  [k in obj]: boolean
}

// typeof: returns the  object with key and values as the type
// keyof: return union from keys of the object 

// using generics 
type objBoolean<T extends {}> ={
 //  T extends {} is a conditional check to check if T is the Object first 
 [k in keyof typeof T]: boolean
}

Now if you use objBoolean on obj you will get


{
  firstname:boolean,
  lastname:boolean
}

implement your Own Pick, Recod ….

Implementation of Record :