Question:
How can I specify a monkey-patched class in the typescript definitions file in JavaScript?

Problem:

Say I have a class A:

class A {

    constructor();


    someFunction(): void;

}


and a class B where I expect an instance of class A as a property:

class B {

    aProperty: A;

}


How can I define typescript definitions (.d.ts) for a class C with a property of class A that is monkey patched to also include a function someOtherFunction(): void;?


Additional information

In class C, class A effectively looks like this:

class A {

    constructor();


    someFunction(): void;

    someOtherFunction(): void;

}


I tried to define class C as follows without any luck:

class C {

    aProperty: A | { someOtherFunction(): void; };

}


Solution:

If you've monkey-patched the class, then it has the new method wherever it's used. You can make the types reflect that by using >declaration merging:

interface A {

    someOtherFunction(): void;

}


>Playground link

That will merge with the types for class A to make someOtherFunction available on instances of A (from a type perspective; the monkey-patching is necessary for it to be true from a runtime perspective).

I don't know that you can scope it, though. As >Konrad pointed out, you can use an intersection rather than a union for the property (aProperty: A & {some other function (): void; };). But again, if it's monkey-patched, it's monkey-patched everywhere. :-)


Suggested blogs:

>Fixing QVariant output issue in Python

>Removing ASCII formatted characters from my CAN messages in Python

>Why `import` does not work in this case (in `exec`)?

>Fix my form calling the wrong Django view error

>How to load static files using Nginx, Docker, and Django?

>How to tell Django "if anything in urlpatterns does not match the GET string?

>How can I browser to render links in streamed content in Django?

>Access the "model" attribute for a ListView in Django for template



Ritu Singh

Ritu Singh

Submit
0 Answers