Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you extend a function in TypeScript?

Tags:

typescript

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) {
    ...
}
like image 281
Will Munn Avatar asked Jul 12 '16 20:07

Will Munn


People also ask

Can you extend type in TypeScript?

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 .

Can functions be extended?

Yes. You can always extend a function by just defining it to be whatever you want outside of its implied domain.

Can we extend function in JavaScript?

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.

What does Extends mean in TypeScript?

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.


1 Answers

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()) {
    // ...
}
like image 73
Mattias Buelens Avatar answered Oct 17 '22 06:10

Mattias Buelens