Skip to content

Type of this is not preserved when class method is used as a value #49438

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

Closed
zawodskoj opened this issue Jun 8, 2022 · 2 comments
Closed

Type of this is not preserved when class method is used as a value #49438

zawodskoj opened this issue Jun 8, 2022 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@zawodskoj
Copy link

zawodskoj commented Jun 8, 2022

Bug Report

πŸ”Ž Search Terms

this type, class, bind

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

class Foo {
    bar = 123;

    method() {
        console.log(this.bar);
    }
}

const instance = new Foo();
const fn1 = instance.method;
fn1(); // compiles, but fails in runtime

const fn2: (this: Foo) => void = instance.method;
fn2(); // does not compile: The 'this' context of type 'void' is not assignable to method's 'this' of type 'Foo'.

// TS allows to coerce `this` in any (and unsafe) way
const fn3: (this: number) => void = instance.method;
fn3.bind(123)(); // compiles, but fails in runtime

πŸ™ Actual behavior

TS assumes this as any

πŸ™‚ Expected behavior

TS should preserve this type when class method is used as a value

@fatcerberus
Copy link

fatcerberus commented Jun 8, 2022

Methods don’t have a this type by default. See #10288 and #7968

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jun 8, 2022
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants