typeof and lookup type in typescript

rubiin

Rubin

Posted on May 2, 2022

typeof and lookup type in typescript
  • The typeof key can be used to extract type from an existing data
const user = {
  name: "Rubin",
  age: 15,
  address: "Kathmandu"
}

type UserType = typeof user  //  {name: string,age:number,address: string}
Enter fullscreen mode Exit fullscreen mode
  • Look up types on the other hand are used to extract a portion from a complex type and create a new type
type requestType = {

  payload: {
    name: string,
    user: number,
    roles: {
      edit: boolean,
      create: boolean,
      read: boolean
    }
  },
   params: {
     id: number,
     type: string
   }
}

// if we want to use type of  params as a type then

type Params = requestType["params"]  //  {id: number,type: string }
type Roles = requestType["payload"]["roles"] //   roles: {edit: boolean,create: boolean,read: boolean}

Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
rubiin
Rubin

Posted on May 2, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related