-
-
Save GianlucaGuarini/0fd037e01039ae200d4e5915ec527846 to your computer and use it in GitHub Desktop.
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'; | |
const compilerOptions = { | |
target: ts.ScriptTarget.Latest, | |
module: ts.ModuleKind.ESNext, | |
strict: true, | |
noEmit: true, | |
lib: [], | |
types: [], | |
}; | |
const code = ` | |
class A; | |
function x<T>(a: T) { | |
return "x"; | |
} | |
function main() { | |
// Here type parameter T is bound to type A. | |
// I want to extract that information. | |
x(new A()); | |
} | |
`; | |
const host = ts.createCompilerHost(compilerOptions); | |
host.getSourceFile = (fileName) => { | |
if (fileName === 'test.ts') { | |
return ts.createSourceFile(fileName, code, ts.ScriptTarget.Latest); | |
} | |
return undefined; | |
}; | |
const program = ts.createProgram(['test.ts'], compilerOptions, host); | |
const typeChecker = program.getTypeChecker(); | |
const sourceFile = program.getSourceFile('test.ts'); | |
function visit(node) { | |
if (node.kind === ts.SyntaxKind.CallExpression) { | |
// Assert the function has at least one parameter | |
console.assert(node.arguments.length === 1); | |
// Get the type of the argument passed to the function | |
const argType = typeChecker.getTypeAtLocation(node.arguments[0]); | |
// Get the type name | |
const typeName = typeChecker.typeToString(argType); | |
console.log(`Type of argument: ${typeName}`); | |
} | |
ts.forEachChild(node, visit); | |
} | |
visit(sourceFile); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment