#typeChecker.getTypeAtLocation is returning "any"

4 messages · Page 1 of 1 (latest)

untold lava
#

I'm trying to use typescript to perform static code analysis and I'm having a lot of trouble of reading types from a transpiled .js file, since it's returning any instead of the type that's on the .d.ts file. From what I understand, typescript itself should automatically pick the types form the d.ts if the file is in the same folder and have the same name.

My setup is:

--folder
-----index.js
-----index.d.ts

And this is my createProgram:

program = ts.createProgram({ oldProgram: program, rootNames: ['/folder/index.js'], options: { target: ts.ScriptTarget.ESNext, jsx: ts.JsxEmit.React, allowJs: true, checkJs: true, module: ts.ModuleKind.NodeNext, baseUrl: '.', esModuleInterop: true, moduleResolution: ts.ModuleResolutionKind.NodeNext, declarationMap: true, declaration: true, lib: ['lib.esnext.d.ts', 'lib.dom.d.ts'], paths: { 'react/jsx-runtime': ['node_modules/react/jsx-runtime'], }, }, });

I already tried a bunch of different options here, but no luck.

The const sourceFiles = program.getSourceFiles(); doesn't pick up the d.ts file automatically into the program context, which I think it should, but I'm not 100% sure. I can do that manually by adding /// <reference path="./index.d.ts" /> at the top of the index.js file. But calling typeChecker.getTypeAtLocation will still return any and not the correct type.

Why isn't typescript correctly resolving types and how can I make it? One workaround that I'm doing right now it's adding the .d.ts file instead of the .js and my code works, but for my use case I actually need to analyise the .js sometimes.

thorn lotus
#

@untold lava I don't think typescript does ever map from JS code to corresponding .d.ts declaration.

#

When you compile .ts code it produces .js and .d.ts file, but TS itself really only looks at the .d.ts files - the replacement happens at the module-import level.

#

And when you use TS with allowJs - TS parses JS code and produces .d.ts files but again, the .d.ts file basically just replaces the JS file as far as TS is concerned when the code is consumed by other projects