Home > Net >  Return arbitrary value type in Object
Return arbitrary value type in Object

Time:09-13

If I have an object with many keys and each value in each key has different value type

type keys = 'typeA' | 'typeB' | ... | 'typeZZZ'
const obj = {
 'typeA': typeA,
 'typeB': typB,
...
'typeZZZ': typeZZZ
}

const destruct = (key: keys): /* what's the return type I can specify? */ => {
  return obj[key] // <- how should I narrow type here?
}

const typeA = destruct('typeA') // <- I want this value type to be `typeA` without using as or if statement

Is it possible to do it?

CodePudding user response:

You can make key generic and only accept a key of obj.

const destruct = <K extends keyof typeof obj>(key: K): typeof obj[K] => {
  return obj[key]
}

The return type would then be obj[K].


Playground

  • Related