Last active
October 11, 2017 16:03
-
-
Save mape/202e8a6c41a40bba2e82ee8743fac2a8 to your computer and use it in GitHub Desktop.
Extract inferred return types from functions that are exported in TypeScript file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(), | |
); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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