Skip to content

Instantly share code, notes, and snippets.

@mape
Last active October 11, 2017 16:03
Show Gist options
  • Save mape/202e8a6c41a40bba2e82ee8743fac2a8 to your computer and use it in GitHub Desktop.
Save mape/202e8a6c41a40bba2e82ee8743fac2a8 to your computer and use it in GitHub Desktop.
Extract inferred return types from functions that are exported in TypeScript file
import fs = require('fs');
import ts = require('typescript');
// Create the language service host to allow the LS to communicate with the host
const servicesHost: ts.LanguageServiceHost = {
getScriptFileNames: () => rootFileNames,
getScriptVersion: (fileName) => files[fileName] && files[fileName].version.toString(),
getScriptSnapshot: (fileName) => {
if (!fs.existsSync(fileName)) {
return undefined;
}
return ts.ScriptSnapshot.fromString(fs.readFileSync(fileName).toString());
},
getCurrentDirectory: () => process.cwd(),
getCompilationSettings: () => ({
target: ts.ScriptTarget.ES2016,
skipDefaultLibCheck: true,
lib: ['lib.es6.d.ts', 'lib.scripthost.d.ts'],
removeComments: true
}),
getDefaultLibFileName: (options) => ts.getDefaultLibFilePath(options),
fileExists: ts.sys.fileExists,
readFile: ts.sys.readFile,
readDirectory: ts.sys.readDirectory,
};
const rootFileNames: string[] = [];
const files: { [k: string]: { version: number } } = {};
// Create the language service files
const services = ts.createLanguageService(
servicesHost,
ts.createDocumentRegistry()
);
const fileName = 'test.ts';
rootFileNames.push(fileName);
files[fileName] = {
version: 0
};
const program = services.getProgram();
const typeChecker = program.getTypeChecker();
const sourceFile = program.getSourceFile(fileName);
ts.isFunctionDeclaration
sourceFile.statements.forEach((statement) => {
const f = statement as ts.FunctionDeclaration
console.log(
f.name!.escapedText,
typeChecker.typeToString(typeChecker.getTypeAtLocation(f.type!)),
typeChecker.typeToString(typeChecker.getReturnTypeOfSignature(typeChecker.getSignatureFromDeclaration(f))),
// typeChecker.typeToString(),
);
});
export function aFunction() {
return 'Obviously a string';
}
export function bFunction() {
return ['Obviously a string'];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment