Search code examples
typescripttypescript-types

How can I get the type from the result of a callback action?


I'm not really sure how to express what I need to do in terms which has made searching for a solution very hard. I've also tried reading the Typescript docs but I couldn't find anything related to what I want. I have this condensed code example of what I'm trying to do:

function test(
  name: string,
  actions: () => {/* I need something else here */}
) {
  return actions()
}

const foo = test('foo', () => ({
  bar() {
    console.log('foo.bar')
  }
}))

foo.bar() // Property 'bar' does not exist on type '{}'.ts(2339)

Is it possible to get Typescript to understand that bar() should be available on foo in this case?


Solution

  • You can use typescript generics

    function test<T>( //Generic type T
      name: string,
      actions: () => T // Callback return value
    ): T { // Whole functions return value
      return actions()
    }
    
    const foo = test('foo', () => ({
      bar() {
        console.log('foo.bar')
      }
    }))
    

    Check it out in the typescript playground