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; };
}
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:
Playground link
That will merge with the types for
class A
to makesomeOtherFunction
available on instances ofA
(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 & { someOtherFunction(): void; };
). But again, if it's monkey-patched, it's monkey-patched everywhere. :-)