简体   繁体   中英

Typescript: How to define overloaded function type

I have created following interface for function overloading

interface IRequestObservableDelegate {
    (url: string | Request, options?: RequestOptionsArgs): Observable<Response>;
    (url: string | Request, body?: string, options?: RequestOptionsArgs): Observable<Response>;
}

My Idea is to pass a function of type above interface to another function

function DoSomething(cb:IRequestObservableDelegate,someCondition:boolean):void;

Following code works

const f1 = (u,o) => obsrevable; // dummy function
DoSomething(f1,somecond);

But this does not work

const f2 = (u,b,o) => obsrevable; // dummy function
DoSomething(f2,somecond);

Any Idea how to define overloaded function type

When you provide multiple call signatures in the interface anything you try to assign to that interface must match all of the call signatures. Your assignment to f2 doesn't match the first signature because it has an extra parameter so you can't use it.

This does actually make sense, because any code using an object that implements the interface might call the function using the first signature and f2 doesn't know how to handle those calls.

What you might do instead would be to define two separate interfaces, one for each signature and then a type IRequestObservableDelegate with is the union of those two interfaces. Then f1 and f2 are each defined to hold the relevant restricted interface but either can still be passed to a function that accepts the union interface. That of course means the code using the union interface has to make assertions about the type of the callback function so you won't lose type safety when calling it.

interface IRequestSimpleObservableDelegate {
    (url: string | Request, options?: RequestOptionsArgs): Observable<Response>;
}
interface IRequestBodyObservableDelegate {
    (url: string | Request, body?: string, options?: RequestOptionsArgs): Observable<Response>;
}

type IRequestObservableDelegate = IRequestSimpleObservableDelegate | IRequestBodyObservableDelegate;

and now I think both assignments should work.

You are missing the optional parameters , you should do it like this:

const f1 = (u,o?) => obsrevable; // dummy function
DoSomething(f1,somecond);

const f2 = (u,b?,o?) => obsrevable; // dummy function
DoSomething(f2,somecond);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM