-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Bound functions and this
context
#28777
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
Comments
This is working as intended. You're taking the bound function values of type type BoundAction = () => void;
type BoundActions = { [key: string]: BoundAction };
class Foo {
action1: BoundAction;
action2: BoundAction;
actions: BoundActions;
// ...
} |
But then I'll lose typechecking inside of callbacks. If I'll make a typo like this: |
Then it's bound it's not of type |
I don't understand. Here's what I'm suggesting in full. It works and produces the expected errors if you say type Action<T> = ( this: T ) => void;
type Actions<T> = {
[ key: string ]: Action<T>;
}
type BoundAction = () => void;
type BoundActions = { [key: string]: BoundAction };
class Foo {
action1: BoundAction;
action2: BoundAction;
actions: BoundActions;
constructor( action: Action<Foo> ) {
this.action1 = action.bind( this );
}
bindAction2( action: Action<Foo> ) {
this.action2 = action.bind( this );
}
bindActions3( action: Action<Foo> ) {
this.actions = {
action: action.bind( this ),
};
}
bindActions4( action: Action<Foo> ) {
return {
action: action.bind( this ),
};
}
hello() {
console.log( 'Hello' );
}
}
const foo = new Foo( function() { this.hello(); } );
const action1 = foo.action1;
action1(); // Ok
foo.bindAction2( function() { this.hello(); } );
const action2 = foo.action2;
action2(); // Ok
foo.bindActions3( function() { this.hello(); } );
foo.actions.action(); // Ok
const actions = foo.bindActions4( function() { this.hello(); } );
actions.action(); // Ok |
Oh. I'm sorry. Now I see. Yes the full example works. I just thought you suggested to change |
Thanks! |
TypeScript Version: 3.2.1, 3.3.0-dev.20181130
Search Terms: bind, strictBindCallApply
Code
Expected behavior:
I just want to bind some functions to the instance of my class and use them as callbacks, event handlers ... Actually those functions are bound so they have proper
this
. If they wouldn't bound then yes —this
would be different.Actual behavior:
I get 3 compile errors:
But compiled js works just fine:
The text was updated successfully, but these errors were encountered: