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
Unexpected type error for accessing known existent members in a ReadonlyArray with noUncheckedIndexedAccessΒ #46922
constx: ReadonlyArray<number>=[0,1,2];constc: number=x[0];/* Unexpected `Type 'number | undefined' is not assignable to type 'number'. Type 'undefined' is not assignable to type 'number'.`*/
π Actual behavior
It returned number | undefined type for all members of the ReadonlyArray.
I think this is expected, x[10] is also number | undefined since your type doesn't retain length information. [0,1,2] as const retains the length information and therefore x[0] is typed as number.
That's right, ReadonlyArray is just a generic array type and doesn't include the length of the array as part of the type, nor does the control flow analyzer track that information (hence why noUncheckedIndexedAccess is optional). If you had gotten this array as an argument to a function call, for example, nothing in its typing says those elements have to be present, so the error is correct.
Activity
tadhgmister commentedon Nov 26, 2021
I think this is expected,
x[10]is alsonumber | undefinedsince your type doesn't retain length information.[0,1,2] as constretains the length information and thereforex[0]is typed as number.fatcerberus commentedon Nov 26, 2021
That's right,
ReadonlyArrayis just a generic array type and doesn't include the length of the array as part of the type, nor does the control flow analyzer track that information (hence why noUncheckedIndexedAccess is optional). If you had gotten this array as an argument to a function call, for example, nothing in its typing says those elements have to be present, so the error is correct.RyanCavanaugh commentedon Nov 29, 2021
ReadOnlyalso doesn't mean immutable. You could get back an array from a function that still is able to mutate it later.The behavior you expect can be achieved from
typescript-bot commentedon Dec 1, 2021
This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.