You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Type guard is not working with noUncheckedIndexedAccess and destructuring #52623
When noUncheckedIndexedAccess is on and you try to use a type guard like typeof list[index] !== undefined, it would not work if index was created via destructuring assignment or from the tuple.
🔎 Search Terms
noUncheckedIndexedAccess index destructuring undefined tuple
// index is a numberconstindex=1// indexD is a numberconst[indexD]=[1]consttuple: [number]=[1]constindexT=tuple[0]constlist: Array<number>=[1,2,3]// Block Aif(typeoflist[index]==='number'){// `num` has a `number` typeconstnum=list[index]}// Block Bif(typeoflist[indexD]==='number'){// `num` has a `number | undefined` typeconstnum=list[indexD]}// Block Cif(typeoflist[indexT]==='number'){// `num` has a `number | undefined` typeconstnum=list[indexT]}
🙁 Actual behavior
Type guard does not work with the num in the Block B and C
🙂 Expected behavior
num in the Block B and C should have the same type as the num in the Block A
changed the title [-]Type guards are not working with `noUncheckedIndexedAccess` and destructuring[/-][+]Type guard is not working with `noUncheckedIndexedAccess` and destructuring[/+]on Feb 5, 2023
Duplicate of #10530. Type narrowing does not occur for indexed access forms e[k] where k is not a literal.
I see... But still quite strange that even when you declare something as a constant literal, for example:
const[indexT]=[1]asconst// here indexT has a type '1', and still doesn't workconstindex: number=1// index has a 'number' type, not literal 1if(typeoflist[indexT]==='number')num=list[indexT]// number | undefinedif(typeoflist[index]==='number')num=list[index]// number
Activity
[-]Type guards are not working with `noUncheckedIndexedAccess` and destructuring[/-][+]Type guard is not working with `noUncheckedIndexedAccess` and destructuring[/+]MartinJohns commentedon Feb 5, 2023
Duplicate of #10530. Type narrowing does not occur for indexed access forms
e[k]wherekis not a literal.fatcerberus commentedon Feb 5, 2023
Workaround: Assign
list[index]to aconstfirst then type-guard that.PunGy commentedon Feb 6, 2023
I see... But still quite strange that even when you declare something as a constant literal, for example:
Very confusing behavior
typescript-bot commentedon Feb 16, 2023
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.