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?
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 }
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With