[英]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.