Home > Mobile >  Generate typescript types depending on generic provided object
Generate typescript types depending on generic provided object

Time:11-05

Try to extend an object with a key depending on the keys of the object provided. is it possible to get this typed?

here is my current code:

const getData = <T extends Record<string, any>>(initState: T) => {
  const temp: Record<string, any> = {}
  for (const [key, value] of Object.entries(initState)) {
    temp[key] = value
    temp['set'   ucFirst(key)] = (value: any) => null
  }
  return temp
}

const a = getData({ test: 'demo' });

a.setTest() // not working

CodePudding user response:

With mapped types and key remapping, you could describe the result your code produces like this:

const getData = <T extends Record<string, any>>(initState: T): T & { [K in keyof T as `set${Capitalize<K & string>}`]: (value: T[K]) => void } => {

Playground

  • Related