I normally add custom knockout binding handlers in JavaScript via
ko.bindingHandlers.myBindingHandler = {...}
but now I have to add them in TypeScript via
ko.bindingHandlers["myBindingHandler"] = {...}
otherwise I get this error because I'm using typescript.d.ts:
The property 'myBindingHandler' does not exist on value of type 'KnockoutBindingHandlers'
I don't like the ["property"]
approach because then I can't reference it or get intellisense on it later.
So, how can I add my custom binding handler to knockout while using definitelyTyped's knockout definition, while also being able to reference my definition via intellisense, etc?
Another dirty way to ignore any kind of type checking:
you can simply ignore it,but this is not a good practice, by casting to
any
you are not defining the type of the propertymyBindingHandler
Defining a custom binding handler
Its actually pretty easy, just add it (
myBindingHandler
) to theKnockoutBindingHandlers
interfaceright before you define your custom binding handler. Please note that you have to do make this addition to the interface, within a.d.ts
file as of version 1.0 (or possibly earlier).bindingHandlers.d.ts
myBindingHandler.ts
Now everything works. This will not overwrite any existing definitions or declarations, so your definition will sit along side of
ko.bindingHandlers.text
, etc.Just be careful, because if you do not include an actual definition of
myBindingHandler
and you reference it elsewhere, it will compile due to the definition you added toKnockoutBindingHandlers
, but it will break at runtime because there is no implementation ofmyBindingHandler
.The documentation for adding custom bindinghandlers in knockoutjs is here
Using fn to add custom functions with TypeScript
Similarly, to add something to
ko.observable.fn
, you'd do this in typescriptand call it with
Note: There are different interfaces for the
subscribable
,observable
,observableArray
, andcomputed
types:ko.subscribable.fn
... add toKnockoutSubscribableFunctions
ko.observable.fn
... add toKnockoutObservableFunctions
ko.observableArray.fn
... add toKnockoutObservableArrayFunctions
ko.computed.fn
... add toKnockoutComputedFunctions
The documentation for adding onto fn in knockoutjs is here