Upon closer examination, it appears that the types (A | B)[]
and A[] | B[]
are essentially interchangeable in TypeScript. The evidence for this can be seen in the following examples:
var test1: number[] | string[] = [1]
var test2: (number | string)[] = ["stuff"]
var test3: (number | string)[] = test1
However, a discrepancy emerges when these types are used in return functions. This disparity is highlighted below:
function getStuff(flag:number): number | string {
if (flag == 0) {
return 1
} else {
return "hello"
}
}
function returnStuff(flag: number): number[] | string[] {
let toReturn: (number | string)[] = [getStuff(flag)]
// It becomes apparent that even though toReturn is of type (number | string)[], attempting to return it
// when the return type should be numbrt[] or string[] will result in failure.
return toReturn;
}
This leads to two fundamental questions:
- What is causing this discrepancy and what steps can be taken to correct it?
- Is there any way to use TypeScript's type system to convert between
number[] | string[]
and(number | string)[]
?