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

Passing bound callback to function taking unbound callback #35293

Closed
danielrentz opened this issue Nov 22, 2019 · 4 comments
Closed

Passing bound callback to function taking unbound callback #35293

danielrentz opened this issue Nov 22, 2019 · 4 comments
Labels
Duplicate An existing issue was already created

Comments

@danielrentz
Copy link

TypeScript Version: 3.7.2

Search Terms: bound unbound callback this parameter

Code

class C { public prop = 1; }
const c = new C();
 
function callUnbound(fn: () => void): void {
    fn();
}

function callBound(fn: (this: C) => void): void {
    //fn(); // compiler error as expected
    fn.call(c); // passes as expected
    callUnbound(fn); // passes unexpectedly (`callUnbound` does not call with context)
}

callBound(function () { console.log(this.prop); });

Expected behavior:
Last line in callBound causes a compiler error.

Actual behavior:
Last line in callBound passes the compiler, and fn will be called without this context.

Playground Link:

Related Issues:

@jcalz
Copy link
Contributor

jcalz commented Nov 22, 2019

Duplicate of #7968

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Nov 22, 2019
@fatcerberus
Copy link

fatcerberus commented Nov 22, 2019

The callBound() call on the last line likely wouldn't be an error even with stricter this typing, because its argument function has no this annotation at all. It's the same principle that you can pass a function with fewer parameters in place of one with more. The callUnbound() call is where I would expect the compiler error, if one were to be produced.

edit: Disregard, I was stupid and misread the issue.

@danielrentz
Copy link
Author

The callBound() call on the last line likely wouldn't be an error even with stricter this typing, because its argument function has no this annotation at all. It's the same principle that you can pass a function with fewer parameters in place of one with more. The callUnbound() call is where I would expect the compiler error, if one were to be produced.

That's what I wanted to express with "Last line in (the function) callBound". :)

@fatcerberus
Copy link

Oops, you’re right, that was a brain fart. I read it as “the last line, callBound, ...” 😬

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