Search code examples
typescripttypescript-typingstypescript2.0tsc

Retrieve return type of function w/o calling the function


Say I have a function like this in TypeScript:

export const foo = function(){

   return {
     a: 1,
     b: true,
     c: 'bar'
   }

};

if I import this function into another file:

import {foo} from './foobar';

My question is - is there a way to get the return type of foo without actually calling foo?


Solution

  • This is now possible with Typescript 2.8

    let foo = function() {
       return {
         a: 1,
         b: true,
         c: 'bar'
       }
    };
    
    type ComplexObj = ReturnType<typeof foo>;  // {a: number, b: boolean, c: string}