Typescript compile api - detect builtin's like Math

109 Views Asked by At

How do you detect a builtin (like Math, console, etc.) with compile API?

1

There are 1 best solutions below

0
On BEST ANSWER

If you have the identifier (ex. the identifier with the text Math), you can get its symbol via TypeChecker#getSymbolAtLocation(node). Once you have the symbol, you can follow it back to its declaration(s), which will allow you to get the source file the declaration exists in. Once you have the source file, you can check if it's from the TypeScript package's lib folder. The lib folder contains all the declarations for all the "built in" types.

For example:

const symbol = checker.getSymbolAtLocation(ident);
const isInLibFiles = symbol?.getDeclarations()
    ?.some(s => s.getSourceFile().fileName.includes("/node_modules/typescript/lib/"))
    ?? false;

That said, there may be a better way I'm just not familiar with.