[英]typescript generic as object key name
我正在使用动态字段调用服务器,服务器将以 object 响应,该字段作为 object 上的键。 我已经尝试了所有这些,但它们给出了所有错误
function callServer<T>(field, value): IResponse<T> {
return api.put(url, { [field]: value })
}
interface IResponse<T> {
[T]: any
}
interface IResponse<T> {
[key: T]: any
}
interface IResponse<T extends string> {
[T]: any
}
这甚至可能吗?
谢谢!
对的,这是可能的! 如果您确保字段类型参数扩展string | number | symbol
string | number | symbol
string | number | symbol
,然后使用Record
来制作 object 结构,效果很好。
function callServer<Field extends string>(field: Field, value: any): Record<Field, any> {
return api.put(url, { [field]: value })
}
// Type is an object with the key of `'fieldName'` with the value of `any`
const test = callServer('fieldName', { value: 'my test value' })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.