Created
February 12, 2018 17:37
-
-
Save gimenete/b0896a3c2055e11cb2a1e8e96e7966d4 to your computer and use it in GitHub Desktop.
Calculate inferred types from a typescript file
This file contains 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 * 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