简体   繁体   中英

typescript generic as object key name

I'm calling the server with a dynamic field, and the server will respond with an object with that field as the key on object. I've tried all these but they give all bunch of errors

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
}

Is this even possible?

Thanks!

Yes, it is possible! If you make sure the field type argument extends string | number | symbol string | number | symbol string | number | symbol and then use a Record to make the object structure, it works wonderfully.

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' })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM