ts-morph icon indicating copy to clipboard operation
ts-morph copied to clipboard

getType returns wrong type in property access expression in JS

Open steinybot opened this issue 1 year ago • 4 comments

Describe the bug

Version: 22.0.0

To Reproduce

import {Project, ScriptKind, SyntaxKind} from "ts-morph";

const project = new Project({});

// This works.
//const className = "Thing"
// This doesn't work.
const className = "Image"

const ts = project.createSourceFile("test.d.ts",
    `
    declare class ${className} {}
    `, { scriptKind: ScriptKind.TS })
const file = project.createSourceFile("test.js",
    `
    class ${className} {}
    ${className}.foo = 'bar'
    `, { scriptKind: ScriptKind.JS })

const statement = file.getStatementByKind(SyntaxKind.ExpressionStatement)
if (statement) {
    const binExp = statement.getChildAtIndexIfKindOrThrow(0, SyntaxKind.BinaryExpression)
    const propAccessExp = binExp.getChildAtIndexIfKindOrThrow(0, SyntaxKind.PropertyAccessExpression)
    const imageId = propAccessExp.getChildAtIndexIfKindOrThrow(0, SyntaxKind.Identifier)
    console.log(imageId.getType().getText())
}

Reproduction: https://github.com/steinybot/bug-reports/tree/ts-morph/wrong-get-type

Expected behavior

It should log typeof Image but it logs new (width?: number, height?: number) => HTMLImageElement

steinybot avatar Apr 10 '24 18:04 steinybot

Pretty sure you're augmenting a globally available Image via some defaultly available DOM types.

lazarljubenovic avatar Apr 12 '24 14:04 lazarljubenovic

Pretty sure you're augmenting a globally available Image via some defaultly available DOM types.

AFAIK the locally defined Image should shadow the global one. That's what it seems to do when I run the code.

This is a minimal reproduction from real code in @pulumi/aws which I don't think does the correct thing at runtime although I haven't checked this specific instance.

steinybot avatar Apr 17 '24 08:04 steinybot

I did some debugging and it gets to resolveNameHelper in the type checker and it traverses up to the SourceFileObject. canHaveLocals returns true but the location.locals is empty for some reason. It looks like if it wasn't empty then it would attempt to lookup from these locals first. Only if it doesn't find it here does it look for it in the globals.

steinybot avatar Apr 17 '24 09:04 steinybot

Although even if locals was not empty it fails the !isGlobalSourceFile(location) check. Perhaps I need to get it to treat it as a ModuleDefinition instead? Not sure how to do that.

steinybot avatar Apr 17 '24 09:04 steinybot