Here's an example (not a good one :p):
type RandomType = {x: number, y: number}
type UnifiedTypes = RandomType | 0
type ArrayOfTypes = Array<(RandomType | UnifiedTypes)[]>
const newIns: ArrayOfTypes = [[0, {x: 10, y: 201}], [0, {x: 10, y: 201}]]
for(let i=0; i < newIns.length; ++i){
for(let j=0; j < newIns[i].length; ++j){
if(newIns[i][j] !== 0){
newIns[i][j].x = 30 // Property 'x' does not exist on type 'UnifiedTypes'. Property 'x' does not exist on type '0'
}
}
}
// Hoewever, when outside of loop compiler runs fine
if(newIns[0][0] !== 0) {
newIns[0][0].x = 33; // no error thrown
}
Narrowing doesn't seem to work when looping through a union typed array so I'm bit lost. Did I miss smt?
By narrowing down which type the indexed element is going to hold, the typescript compiler should be able to figure out the type of the element array in the specified index and hence assignement occurs safely.