1

Refer to: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API, I want to get type of node in AST.

It is successful for angular project because it is written using typescript and tsconfig.json exists.

When I try to analyze react app which is written using javascript

const program = ts.createProgram({
    rootNames: [fileName],
    options: {
        strict: true,
        target: ts.ScriptTarget.ES2015,
        allowJs: true,
        checkJs: true
    }
})
const typeChecker = program.getTypeChecker();
... ...

I get: typechecker.getTypeAtLocation(node).getSymbol() is undefined.

I assume options of ts.createProgram is wrong.

1
  • I think typeChecker.getTypeAtLocation(node) might be returning the error type. Are there any diagnostics returned by ts.getPreEmitDiagnostics(program)? Commented May 14, 2019 at 19:46

1 Answer 1

1

the option: moduleResolution: ts.ModuleResolutionKind.NodeJs is key.

const program = ts.createProgram({
    rootNames: [file1],
    options: {
        strict: true,
        target: ts.ScriptTarget.ES2015,
        allowJs: true,
        checkJs: true,
        moduleResolution: ts.ModuleResolutionKind.NodeJs
    }
})

The above works for React JS.

Sign up to request clarification or add additional context in comments.

1 Comment

For some background, this solution depends on the scenario and the reason this occurs is because when targeting ES2015 or above, the default module resolution will change from NodeJs to Classic. So this isn't because a JS file was being analyzed and what you were probably getting was the unknown type. Read more in my answer here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.