TypeScript: Can I provide a type alias for an overloaded function signature? -


is possible create type alias overloaded function signature?

for example, have function like:

function whenchanged(scope: ng.iscope, fn: ()=>void): ()=>void; function whenchanged(fn: ()=>void, truthy:any): ()=>void; function whenchanged(a,b): ()=>void {     //... } 

i create type alias overloaded signature save repetition, , make use of in other places need describe type of function.

i tried:

type wc1 = (scope: ng.iscope, fn: ()=>void) => ()=>void; type wc2 = (fn: ()=>void, truthy:any) => ()=>void; type whenchanged = wc1 | wc2;  const whenchanged: whenchanged = (a,b) => {     //... }; 

but trying use function, error along lines of "cannot invoke expression type lacks call signature".

i cannot offhand see in docs type aliasing function overloads.

since have function whenchanged:

function whenchanged(scope: ng.iscope, fn: ()=>void): ()=>void; function whenchanged(fn: ()=>void, truthy:any): ()=>void; function whenchanged(a,b): ()=>void {     //... } 

the simplest way type alias type use typeof type query:

type whenchanged = typeof whenchanged; 

the next, straightforward way create type alias use overloaded function signature (which looking for):

type whenchanged = {   (scope: ng.iscope, fn: () => void): () => void;   (fn: () => void, truthy: any): () => void; } 

(which see in quickinfo if hover on typeof definition in editor.) note don't need use interface if don't want to.


the next thing similar doing, problem overload intersection, not union. both signatures:

type wc1 = (scope: ng.iscope, fn: ()=>void) => ()=>void; type wc2 = (fn: ()=>void, truthy:any) => ()=>void; type whenchanged = wc1 & wc2; // and, not or 

be careful intersections of function signatures not commutative, because represent overloads. means following type not technically same:

type notwhenchanged = wc2 & wc1; // different type 

since overload resolution take place in different order.

note can't call function of type wc1 | wc2 since call signatures different compiler can't tell if function wc1 or wc2.


okay, there go. hope helps; luck!


Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -