Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constrain return type from argument function

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

like image 875
david_adler Avatar asked Mar 17 '26 04:03

david_adler


1 Answers

You can define returned key type as generic parameter (it will be inferred as a single key and not union of all possible keys):

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

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

Playground

like image 169
Aleksey L. Avatar answered Mar 19 '26 16:03

Aleksey L.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!