Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested mapped types in TypeScript

Tags:

typescript

I have this type:

type Requests = {
  "/endpoint": {
    POST: {
      body: any
      response: any
    }
    // ...
  }
  // ...
}

I want to map response to another value, but I get an error in vscode:

export type API = {
  [route in keyof Requests]: {
    [method in keyof Requests[route]]: {
      body: Requests[route][method]["body"] // 🚨 Type '"body"' cannot be used to index type 'Requests[route][method]'
      response: Requests[route][method]["response"] | { error: any } // 🚨 Type '"request"' cannot be used to index type 'Requests[route][method]'
    }
  }
}

Is there any way to accomplish this?

like image 639
MHebes Avatar asked Sep 01 '25 03:09

MHebes


1 Answers

This should do what you want

type Requests = {
    "/endpoint": {
    POST: {
        body: string
        response: number
    }
    // ...
    },

}


export type API = {
    [route in keyof Requests]: {
        [method in keyof Requests[route]]: {
        body: Requests[route][method] extends { body: infer R } ? R : never
        response: (Requests[route][method] extends { response: infer R } ? R : never) | { error: any }
        }
    }
}
like image 147
Countingstuff Avatar answered Sep 02 '25 16:09

Countingstuff