Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return type from function that takes a function as a parameter

I did a bad job at asking this question earlier, thought I had the answer, but ended up not having it.

I’ve created a typescript playground with the example code.

I’m looking to create a function (A) that takes a mapping function (B) as a parameter. The return value of A depends on the return value of B. I’m not sure how to type this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const myObject = {
  a: 1,
  b: 2
} as const

type MapperFunction = <R>(arg: typeof myObject) => R
const identity = (arg: any) => arg

const myFunction = (mapper: MapperFunction = identity) => mapper(myObject)

const theValueOfA = myFunction(({a}) => a)
const theValueOfAPlusB = myFunction(({a,b}) => a+b)

The above doesn’t work because I get errors about R, which makes me think I should be using infer instead of generics, but I’m not sure how to use it.

>Solution :

If I understand you correctly, you can just pass through the generic:

const myObject = {
  a: 1,
  b: 2
} as const

type MapperFunction<R> = (arg: typeof myObject) => R
const identity = (arg: any) => arg

const myFunction = <R,>(mapper: MapperFunction<R> = identity) => mapper(myObject)

const theValueOfA = myFunction(({a}) => a)
const theValueOfAPlusB = myFunction(({a,b}) => a+b)

Then the TS-compiler infers the types correctly.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading