azulBonnet
azulBonnet

Reputation: 889

Setting Up a Knockout Extender with Typescript (2018)

I am attempting to follow the example laid out here: Knockout typescript extenders

In each of these files I actually have a custom KnockoutBindingHandler as well that works, so I thought that putting along side the binding handler would be appropriate and work but no such luck.

I have a customKoBindings.d.ts

import * as ko from "knockout"

interface KnockoutExtenders {
    logChange: (target: KnockoutObservable<any>) => KnockoutObservable<any>;
}

extensions.ts

/// <reference path="./customKoBindings.d.ts" />

import * as ko from "knockout"   

export class KnockoutExtensions {
    constructor() {
ko.extenders.logChange = function (target) {
            target.subscribe(function (newValue) {
                console.log(newValue);
            });
            return target;
        };
    }
}

Error TS2339 (TS) Property 'logChange' does not exist on type 'KnockoutExtenders'.

I saw someone reference their new extender like this: ko.extenders["logChange"]

but even still I cannot do this:

this.end = ko.observable(end).extend({logChange});

Cannot find name "logChange"

Is there a new syntax to do this or am I just missing something?

Upvotes: 1

Views: 544

Answers (2)

Gopal Krishnan
Gopal Krishnan

Reputation: 1116

You could use jquery extend() function to do the same thing (assuming you have imported jquery as 'jquery')

jquery.extend(ko.extenders,
{
    logChange: function (target) {
        target.subscribe(function (newValue) {
            console.log(newValue);
        });
        return target;
    }
});

Upvotes: -1

caseyWebb
caseyWebb

Reputation: 2086

TypeScript files can be either "ambient" or "modules" — modules are anything that use import or export — and the way you have to do declaration merging is dependent on which type of file it is.

To merge declarations in a module, you have to use the declare keyword. So, you've actually got 2 ways to fix this...

1) Remove import * as ko from "knockout" from your declaration file so that it is parsed as ambient.

2) Add declare before interface in your declaration file.

Upvotes: 3

Related Questions