Suggestion
π Search Terms
Array Destructuring, noUncheckedIndexedAccess, length check
β
Viability Checklist
My suggestion meets these guidelines:
β Suggestion
A length check with length more than zero should eliminate undefined from possible values when destructuring.
Looking at the example below, it's impossible that destructuring [unshifted,...rest] from the array could lead to unshifted being undefined, since the length is checked first. Nevertheless when noUncheckedIndexedAccess is set in Tsconfig, it treats undefined as a possible path.
function unshiftOrNothing(items:number[]) : number{
if(items.length > 0){
const [unshifted, ...rest] = items;
return unshifted;
}
return 0;
}
π Motivating Example
I have encountered this a lot when manipulating 'immutable' arrays e.g. for queues or redux state which require the use of destructuring, since array methods change the array.
I can't identify a type-safe alternative or check which ensures that the typescript compiler picks up on the fact the first item must be set.
π» Use Cases
A workaround is to lie to the compiler that items is a tuple containing at least one item. However, I don't know what knock-on effect that has on e.g. type guarantees about ...rest - it's presumably expected to be a zero-length tuple which might break other things.
function workaround(items:number[]) : number{
if(items.length > 0){
const [unshifted, ...rest] = items as [number];
return unshifted;
}
return 0;
}
Suggestion
π Search Terms
Array Destructuring, noUncheckedIndexedAccess, length check
β Viability Checklist
My suggestion meets these guidelines:
β Suggestion
A length check with length more than zero should eliminate
undefinedfrom possible values when destructuring.Looking at the example below, it's impossible that destructuring
[unshifted,...rest]from the array could lead tounshiftedbeing undefined, since the length is checked first. Nevertheless when noUncheckedIndexedAccess is set in Tsconfig, it treatsundefinedas a possible path.π Motivating Example
I have encountered this a lot when manipulating 'immutable' arrays e.g. for queues or redux state which require the use of destructuring, since array methods change the array.
I can't identify a type-safe alternative or check which ensures that the typescript compiler picks up on the fact the first item must be set.
π» Use Cases
A workaround is to lie to the compiler that items is a tuple containing at least one item. However, I don't know what knock-on effect that has on e.g. type guarantees about
...rest- it's presumably expected to be a zero-length tuple which might break other things.