![](/img/trans.png)
[英]Typescript how to create a nested interface objects using mapped types?
[英]Nested mapped types in TypeScript
我有这种类型:
type Requests = {
"/endpoint": {
POST: {
body: any
response: any
}
// ...
}
// ...
}
我想将response
映射到另一个值,但在 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]'
}
}
}
有什么办法可以做到这一点吗?
这应该做你想做的
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 }
}
}
}
即使列表是有限且已知的,打字稿似乎也无法真正概括可能属于该类型的任何键。 但是很容易帮助它。
如果您指定类型的一般格式:
type RequestsFormat = Record<string, { [key: string]: { body: any, response: any } }>
然后扩展:
interface Requests extends RequestsFormat {
"/endpoint": {
POST: {
body: any
response: any
}
}
}
然后打字稿可以找出其余的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.