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

I encountered a 'not assignable type' error when I turned on the 'noUncheckedIndexedAccess' option. #54353

Closed
hotsoycandy opened this issue May 23, 2023 · 4 comments
Labels
Duplicate An existing issue was already created

Comments

@hotsoycandy
Copy link

hotsoycandy commented May 23, 2023

Bug Report

πŸ”Ž Search Terms

  • type guard
  • noUncheckedIndexedAccess

πŸ•— Version & Regression Information

Typescript version that I tried: 4.9.5, 5.0.4, 5.1.0-beta

⏯ Playground Link

Make it sure that the "noUncheckedIndexedAccess" option is turned on.

Playground link

πŸ’» Code

{
  "compilerOptions": {
    "noUncheckedIndexedAccess": true
  }
}
const fruits: Record<string, string> = { apple : 'best', orange: 'good' }

function getFruit (fruitName: string): string {
    if (typeof fruits[fruitName] === 'string') {
        // Type 'string | undefined' is not assignable to type 'string'.
        // Type 'undefined' is not assignable to type 'string'.(2322)
        return fruits[fruitName]
    }
    return 'nothing'
}

πŸ™ Actual behavior

Type guard doesn't work properly and typescript occurs not assignable type error when using the "noUncheckedIndexedAccess" option.

πŸ™‚ Expected behavior

The type guard works properly even the "noUncheckedIndexedAccess" option is turned on.

For example, fruits[fruitName] should be 'string', not 'string | undefined'

@MartinJohns
Copy link
Contributor

It's working as intended / a known design limitation with many many issues opened already, and it really needs to be added to the FAQ.

Indexed access is not narrowed, unless the key is a literal.

@jcalz
Copy link
Contributor

jcalz commented May 23, 2023

Tracked at #10530

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label May 23, 2023
@microsoft-github-policy-service

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

@microsoft-github-policy-service

This issue has been marked as a 'Duplicate' 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
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants