Skip to content

Instantly share code, notes, and snippets.

@gimenete
Created February 12, 2018 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gimenete/b0896a3c2055e11cb2a1e8e96e7966d4 to your computer and use it in GitHub Desktop.
Save gimenete/b0896a3c2055e11cb2a1e8e96e7966d4 to your computer and use it in GitHub Desktop.
Calculate inferred types from a typescript file
import * as ts from 'typescript'
import * as util from 'util'
const program = ts.createProgram(['src/foo.ts'], {
target: ts.ScriptTarget.ES5,
module: ts.ModuleKind.CommonJS
})
const typeChecker = program.getTypeChecker()
const findFunctions = (parent: ts.Node) => {
parent.forEachChild(node => {
if (ts.isArrowFunction(node)) {
const type = typeChecker.getTypeAtLocation(node)
for (const signature of type.getCallSignatures()) {
const returnType = signature.getReturnType()
console.log('return', typeChecker.typeToString(returnType))
if (returnType.flags === ts.TypeFlags.Number) {
console.log('returns a number')
} else if (returnType.flags === ts.TypeFlags.Object) {
console.log('returns an object')
returnType.getProperties().forEach(property => {
console.log(
'property name',
property.getName(),
typeChecker.typeToString(
typeChecker.getTypeOfSymbolAtLocation(property, property.valueDeclaration!)
)
)
})
}
}
}
findFunctions(node)
})
}
for (const sourceFile of program.getSourceFiles()) {
if (!sourceFile.isDeclarationFile) {
findFunctions(sourceFile)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment