Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript mutiple call signature for exported function

Tags:

typescript

I have the following code:

module array {
  export function contains(arr: Array, item: any): bool { // implementation }
}

What I want to be able to have is either union type ( in the example above Array, NodeList and IArguments should be possible) or multiple signatures for the exported function. I seem to not be able to do either.

I tried declaring the function multiple times with the different typing of the arguments, but the compiler complains for the lack of return statement - there is no point of proving implementation for a declaration used only for type checking of the arguments (and makes the code verbose). I think a much better thing would be to have union types, no?

So the question is: how do I achieve type check for functions where the allowed argument is of different type (in this case - array like object), but the implementation is the same, without having to copy/paste the implementation (basically a simple 'return false' probably will do in the declarations before the last one, but still seems like a bad idea).

like image 266
Peter StJ Avatar asked Nov 25 '12 12:11

Peter StJ


1 Answers

You could use the any keyword to have a dynamic parameter:

export function contains(arr: any[], item: any): bool { // implementation }

Or if you know the types you want to allow, you can overload the function:

export function contains(arr: string[], item: string): bool;
export function contains(arr: number[], item: number): bool;
export function contains(arr: any[], item: any): bool { // implementation }

I've used string and number as an example - but your can use whatever types you like. I also assumed that if you have a list of strings, you'd be looking for a string item but you can change this if it isn't the case.

The final function isn't callable - you can only access it via the overloads.

like image 85
Fenton Avatar answered Sep 27 '22 20:09

Fenton