打字稿通用作为对象键名

时间:2021-06-03 18:11:54

标签: typescript

我用一个动态字段调用服务器,服务器将响应一个以该字段作为对象键的对象。我已经尝试了所有这些,但它们给出了所有错误

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
}

这甚至可能吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

是的,这是可能的!如果您确保字段类型参数扩展 string | number | symbol,然后使用 Record 来创建对象结构,它会非常有效。

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' })
相关问题