Skip to content

Inconsistent type when using noUncheckedIndexedAccessΒ #61957

@Stadly

Description

@Stadly

πŸ”Ž Search Terms

noUncheckedIndexedAccess incorrect undefined

πŸ•— Version & Regression Information

N/A

⏯ Playground Link

https://www.typescriptlang.org/play/?noUncheckedIndexedAccess=true#code/CYUwxgNghgTiAEYD2A7AzgF3jAXPASuEjMADyYwCWKA5gDTwXU0B8A3AFAcBmArimAyVU8bkiQAKANYgAnnia0AlAoxVa8AN4d48GbPgBeeAHI0SALYgMAC2Ym28APRP4AYUtWUWJLyy3KNAYoFGB4WwQQGBhieGBAqAAHRJBYNABCLl0YAG19AF14AH4i4xMAI1gHHWxrXhgUbDy5fMcXeABRaOI8ABVZFNNFGngAH3h+UG5qEGATeED4FCQsKDQ0ShoUKHKIBAwkcIGEMzV7ADoOAF8gA

πŸ’» Code

declare const r: Record<string, string>;

function foo(key: string): string {
  key = 'something'; // Comment out this, and the error disappears!

  r[key] ??= 'bar';
  return r[key]; // Error: Type 'string | undefined' is not assignable to type 'string'.
}

πŸ™ Actual behavior

Error: Type 'string | undefined' is not assignable to type 'string'.

Incorrect because r[key] cannot be undefined.

πŸ™‚ Expected behavior

No error, and that the behavior is the same whether or not the line key = 'something'; is commented out.

Additional information about the issue

Originally filed in typescript-eslint: typescript-eslint/typescript-eslint#11343

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions