When iterating through an array, it is necessary to distinguish between two potential types of elements:
- either each element is a string, or
- each element is an array of strings.
function _addDataAtIndex(
totalData: Array<string | string[]>,
dataToAdd: Array<Array<string | string[]>>,
addIndex: number,
) {
dataToAdd.forEach((dataArr) => {
if (dataArr.every((x) => typeof x === 'string')) {
// each value is a string - insert the entire array
totalData.splice(addIndex, 0, dataArr);
} else {
totalData.splice(addIndex, 0, dataArr[0]);
}
});
}
However, TypeScript appears unable to deduce the type of nested arrays even with robust type guards. Despite needing the guard for correctness, there is an additional step where I have to cast the array as dataArr as string[]
. This process seems unnecessary and fragile, prompting me to seek a cleaner alternative for type guarding.
I have explored various solutions from sources, including custom type guard functions, but they have not proven effective either, as shown in this playground.
Is there a more straightforward way to discern between string | string[]
without altering the core structure? The only solution that comes to mind involves transforming the inner values into objects based on a custom union interface, which feels overly intricate for this scenario.