Home > Mobile >  Constrain return type from argument function
Constrain return type from argument function

Time:11-14

I have a function taking a function as an argument. The argument function returns one of a few enums. How do I infer the type of the wrapper function by using the return type of the argument function.

I think much easier explained as an example:

const foo = { a: 1, b: '2' }

function h(k: (() => 'a' | 'b')) {
  return foo[k()]
}

const d = h(() => 'a') 
// expected: d should be of type number
//   actual: d is of type number | string

playground

CodePudding user response:

You can define returned key type as generic parameter:

function h<K extends keyof typeof foo>(k: (() => K)) {
  return foo[k()]
}

const d = h(() => 'a') // now number

Playground

CodePudding user response:

Found a workaround / solution but it's not pretty

function h<T extends (() => 'a' | 'b')>(k: T) {
  return foo[k()] as typeof foo[ReturnType<T>]
}

playground

  • Related