I help maintain a JavaScript library that produces spy functions which allow you to inspect how a passed-in function was called (mainly for use in unit testing).
The library creates a function that has additional properties on it that allow you to inspect the calls.
Is it possible to create a TypeScript definition that will allow the function to be passed in to methods that require a function AND have extra properties?
This is invalid, but something like:
class Spy extends function {
wasCalled: () => boolean;
...
}
Which would allow me to pass a spy into a function with this signature:
function subjectUnderTest(callback:() => void) {
...
}
To extend types in TypeScript, we can use the extends keyword. to create the UserEvent interface that extends the Event type. We extend it by adding the string UserId field in UserEvent and inheriting the rest from Event .
Yes. You can always extend a function by just defining it to be whatever you want outside of its implied domain.
We can also create Javascript Function by extending Javascript classes, like this. Let us extend this class with Child function like this, function Child(props) { let parent = new BaseClass(props) const getMessage = () => `Message is ${parent.
extends means it gets all from its parent. implements in this case it's almost like implementing an interface. A child object can pretend that it is its parent... but it does not get any implementation.
Yes, the TypeScript handbook calls this a "hybrid type", because it's a combination of a function type and a regular interface.
interface Spy {
(foo: string, bar: number) : boolean; // Just an example
wasCalled() : boolean;
}
var spy : Spy = createASpySomehow();
var result = spy("foo", 123);
if (spy.wasCalled()) {
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With