Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extended Class Static methods don't refer to correct this #48414

Closed
sean256 opened this issue Mar 25, 2022 · 3 comments
Closed

Extended Class Static methods don't refer to correct this #48414

sean256 opened this issue Mar 25, 2022 · 3 comments

Comments

@sean256
Copy link

sean256 commented Mar 25, 2022

Bug Report

πŸ”Ž Search Terms

  • static class this reference

πŸ•— Version & Regression Information

I can replicate this bug in all versions provided by the typescript playground, including Nightly:

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

class SomeParentClass {
    private foo: string;
    constructor(foo: string) {
        this.foo = foo;
    }

    getFoo() {
        return this.foo;
    }

    static SomeStaticFactory() {
        return new this('hello world');
    }
}

const someParentInstance = SomeParentClass.SomeStaticFactory();
console.log(someParentInstance.getFoo());

class SomeChildClass extends SomeParentClass {
    someNewMethod() {
        return 'it works';
    }
}

const someChildInstance = SomeChildClass.SomeStaticFactory();
console.log(someChildInstance.someNewMethod()); // Property 'someNewMethod' does not exist on type 'SomeParentClass'.(2339)

πŸ™ Actual behavior

A subclass which uses a Static method of the parent references the wrong this. In the above example, someChildInstance which is returned from SomeChildClass.SomeStaticFactory(); DOES have someNewMethod, but TypeScript barfs on it.

πŸ™‚ Expected behavior

I expect TypeScript to understand that the return type from SomeChildClass.SomeStaticFactory(); is an instance of SomeChildClass and not SomeParentClass

@MartinJohns
Copy link
Contributor

Sounds like a duplicate of #5863. You can't type the return value of SomeStaticFactory as this because it's static.

@MartinJohns
Copy link
Contributor

Just pointing out that code like this is unsound in TypeScript. It's legible to provide a different incompatible constructor in your subclass, which would result in new this('hello world') to result in a runtime error.

class SomeChildClass extends SomeParentClass {
    constructor(n: number) {
        super('bla')

        // Causes: n.toExponential is not a function 
        n.toExponential();
    }
}

@sean256
Copy link
Author

sean256 commented Mar 25, 2022

#5863 does in fact cover this

@sean256 sean256 closed this as completed Mar 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants