With a union of array types (NOT an array of unions, e.g. Foo[] | Bar[]
, not (Foo|Bar)[]
), is it possible to call something like Array.prototype.map on the union to the effect of safely mapping each union variant to a new value with the SAME TYPE (e.g. same variant, but perhaps changing some fields, etc).
Here is an example:
type HomogenousLetters = 'a'[] | 'b'[];
const array: HomogenousLetters = ['a', 'a', 'a'] as HomogenousLetters;
Now, suppose we wanted to map between this array and one of the same union variant.
We might want to call Array.prototype.map
, but this fails to compile in even a trivial case.
// ERROR: Type '("a" | "b")[]' is not assignable to type '"a"[] | "b"[]'.
const mappedArray: HomogenousLetters = array.map((letter) => letter);
I understand this is reasonable behaviour - the type signature of Array.prototype.map() gives no guarantee that homogenous inputs give homogenous outputs (i.e. that each "letter" in array will be of the same union variant), but in that case, how COULD we ensure this?