extract inferred return type with typescript API

422 views Asked by At

I can interact with the typescript compiler API to compile *.ts to *.js

import * as ts from "typescript";

const source = "function foo(xs: Array<number>) { let total=0; for (const x of xs) { total += x; } return total; }";

let result = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS }});

console.log(JSON.stringify(result, null, 4));

Is there any way I can get the inferred return type of foo?

2

There are 2 answers

1
AdiHarif On BEST ANSWER

A possible way of obtaining the return type is using the compiler API's type checker:

  1. First you'll need to create an AST out of your source code using createProgram
  2. Get a type checker for that program with getTypeChecker
  3. Find the AST node of that function declaration
  4. Extract its signature of that declaration using getSignatureFromDeclaration
  5. Extract the signature's return type using getReturnType (this will get a ts.Type object)

There might be an easier way to obtain what you require, but this one worked for me.

for example, if your function is in fun.ts:

const program = ts.createProgram(['fun.ts'])
const checker = program.getTypeChecker()
const sourceFile = program.getSourceFiles().filter(sf => !sf.isDeclarationFile)[0] // to filter all unwanted declaration files
const decl = sourceFile.statements[0] as ts.FunctionDeclaration
const retType = checker.getSignatureFromDeclaration(decl)!.getReturnType()
0
OrenIshShalom On

Based on @AdiHarif's answer I'm adding my final version1:

import * as ts from "typescript";

const options = { target: ts.ScriptTarget.ES5, module: ts.ModuleKind.CommonJS }
const program = ts.createProgram(['example.ts'], options)
const checker = program.getTypeChecker()
const sourceFile = program.getSourceFiles().filter(sf => !sf.isDeclarationFile)[0] // to filter all unwanted declaration files
const decl = sourceFile.statements[0] as ts.FunctionDeclaration
const retType = checker.getSignatureFromDeclaration(decl)!.getReturnType()
console.log(retType);

When I used the following example.ts:

function foo(x: number) {
  return `X = ${x}`;
}

I got the correct answer:

$ npx tsc answer.ts
$ node answer.js | grep 'intrinsicName'
  intrinsicName: 'string',

1 Typescript compiler complained about missing options