When I try to access array that has type of either number[] | number with index I get error for subarray eventhough I check if element is of array type. To make things more confuse when I store reference to subarray in to variable it works without errors?
const minuteRange = [1, 2, 3, 4, [7, 9], [11, 13]];
const minRange = minuteRange;
// const lastEl: number[] | number = minRange[minRange.length - 1] ?? 0;
// IF I REPLACE minRange[minRange.length - 1] ( last element in that array with lastEL up it works without error)
const lastMinuteRangeNum = Array.isArray(minRange[minRange.length - 1])
? minRange[minRange.length - 1][1]
: minRange[minRange.length - 1] ?? 0;
D, and you cannot just let the compiler infer the type using its default algorithm since you also get a too-wide type. You could instead use aconstassertion to ask the compiler to prefer more specific types, like this playground link shows. Does that work for you or am I missing something? (Please mention @jcalz to notify me if you reply.)minRange.length - 1isnumber, which is too wide for the compiler to perform control flow narrowing. See the answers to the linked questions. The workaround is, as you've already noticed, to save the problematic index result into a separate variable and check that.