Skip to content

Instantly share code, notes, and snippets.

@GianlucaGuarini
Forked from surma/typeargs.ts
Last active January 21, 2025 12:50
Show Gist options
  • Save GianlucaGuarini/0fd037e01039ae200d4e5915ec527846 to your computer and use it in GitHub Desktop.
Save GianlucaGuarini/0fd037e01039ae200d4e5915ec527846 to your computer and use it in GitHub Desktop.
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