Skip to content

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

Closed

Description

@chrisirhc

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.

Activity

  1. tadhgmister commented on Nov 26, 2021

    @tadhgmister

    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.

  2. fatcerberus commented on Nov 26, 2021

    @fatcerberus

    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.

  3. RyanCavanaugh commented on Nov 29, 2021

    @RyanCavanaugh
    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]; 
  4. typescript-bot commented on Dec 1, 2021

    @typescript-bot
    Contributor

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

  5. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions