Closed
Description
Search Terms
Union of singletons vs singleton of union, one-element array, single-value array, singleton.
Intersection of 1-tuples should be the same as 1-tuple of the intersection.
Suggestion
As a 1-tuple, or single-element array, contains only one wrapped value, the exact same type operations that are applied to them also apply to their elements. That is, saying "a 1-tuple containing either A or B" is the same as saying "either a 1-tuple containing A, or a 1-tuple containing B". This applies both to type unions and type intersections.
This all should be true in TypeScript:
[A|B|C] === [A|B] | [C] === [A] | [B] | [C]
[A|B] & [C] === [(A|B)&C] === ([A]|[B])&[C]
// where A === B means both A is assignable to B and B is assignable to A
[A|B|C] ⊂ Array<A|B|C>
[A|B|C] ⊂ A[] | B[] | C[]
// where A ⊂ B means A is assignable to B, but B is not assignable to A
Use Cases
type value = string | number;
type array = string[] | number[];
function(a: value | array)
{
const arr = Array.isArray(a) ? a : [a]; // this should work
}
Examples
See Use Cases, I couldn't come up with another example that would be different enough to be worth mentioning.
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.