Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unexpected type error for accessing known existent members in a ReadonlyArray with noUncheckedIndexedAccess #46922

Closed
chrisirhc opened this issue Nov 25, 2021 · 4 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@chrisirhc
Copy link

chrisirhc commented Nov 25, 2021

Bug Report

πŸ”Ž Search Terms

non-existent members, ReadonlyArray
Referenced #13778 (comment) .

πŸ•— Version & Regression Information

noUncheckedIndexedAccess was introduced in 4.1.

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

const x: ReadonlyArray<number> = [0, 1, 2];
const c: 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.

πŸ™‚ Expected behavior

Expected known members to be typed number.

@tadhgmister
Copy link

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.

@fatcerberus
Copy link

fatcerberus commented Nov 26, 2021

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.

@RyanCavanaugh RyanCavanaugh added the Working as Intended The behavior described is the intended behavior; this is not a bug label Nov 29, 2021
@RyanCavanaugh
Copy link
Member

ReadOnly also 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

const x = [0, 1, 2] as const;
const c: number = x[0]; 

@typescript-bot
Copy link
Collaborator

This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

5 participants