Multiple valid types, multiple array member types

Topics: General
Sep 13, 2013 at 9:42 AM
If there any way for a member / argument type to be specified as: (e.g.)
  • a 'string' or a 'number' (a: string | number)
  • an 'array of string' or 'array of number' (a: string[] | number[])
  • an 'array of string and number' (a: { string | number } [])
I think arguments are somewhat covered by multiple signatures, but I'm not sure they can handle the other scenarios.

Thanks
Sep 13, 2013 at 12:16 PM
I asked for this sometime ago, but there is no way currently to do this. The way to go is just use "any".

There are some implications about how to show code completion for this, or how the compiler would check for the correct usage. The probable way to handle this would be to treat it as "any" and don't check anything, and if you are going to do that, just use "any" anyway.

For variables, there would be no real benefits. For functions, there are already overloads that can handle this.
The only place I miss this is member declarations, where an instance variable could be a number or a function to a number, but not a string for example.
Developer
Sep 13, 2013 at 10:25 PM
No, there is no notion of 'union' types in TypeScript at the moment. It's possible you could find a workaround with generic arguments and appropriate constraints on them that establish the classes of operations you want to permit.