After analyzing the given input file:
function foo (s: string) {
console.log(s)
}
I am looking to automatically determine the data type of s
within console.log(s)
. My goal is to replicate the functionality that VSCode uses to display the type of s
when hovering over it.
https://i.sstatic.net/RkmPO.png
This code snippet represents my current progress.
const ts = require("typescript");
const sourceCode = `
function (s: string) {
console.log(s)
}
`;
const sourceFile = ts.createSourceFile(
"test.ts",
sourceCode,
ts.ScriptTarget.Latest
);
const functionDeclaration = sourceFile.statements[0];
const identifier =
functionDeclaration.body.statements[0].expression.arguments[0]; // the s in console.log(s)
const typeChecker = ts.createTypeChecker(ts.createProgram(["test.ts"], {}));
const type = typeChecker.getTypeOfSymbolAtLocation(identifier);
console.log(typeChecker.typeToString(type));
The expected result should be "string", but the actual output returned is "any".