Home > OS >  Return type from function that takes a function as a parameter
Return type from function that takes a function as a parameter

Time:02-01

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.

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.

CodePudding user response:

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.

  • Related