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).
You could use the
anykeyword to have a dynamic parameter:Or if you know the types you want to allow, you can overload the function:
I’ve used
stringandnumberas 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.