Code:
export class ViewModel {
public users: knockout.koObservableArrayBase;
constructor () {
this.users = ko.observableArray([]);
this.removeUser = this.removeUser.bind(this);//<-- Here compiller shows error
}
removeUser(user: User): void {
this.users.remove(user);
}
}
Html:
<table>
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody data-bind="foreach: users">
<tr>
<td><a href="#" data-bind="click: $root.removeUser">Remove</a></td>
<td data-bind="text: name"></td>
<td data-bind="text: surname"></td>
</tr>
</tbody>
</table>
Problem is in removeUser method. By default, if I don’t bind context, this == UserToDelete – not viewModel object. If I adding to constructor: this.removeUser = this.removeUser.bind(this); (manually enforce context), then context is as needed this == viewmodel, but then TypeScript complains for “Cannot convert Function to (user:User)=>void requires a call signatures, but Function lacks one.”
I’m not familiar with ko so perhaps there is a better way to solve the context switching, but your typescript compiler error is caused by ‘bind’ returning type ‘Function’ which is incompatible with the type of ‘removeUser’. You should be able to solve this by casting the returned function into the original type signature as follows: