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

TypeScript failing to narrow field types indexed w/ const assertions #45965

Closed
bsuth opened this issue Sep 20, 2021 · 3 comments · Fixed by #45974
Closed

TypeScript failing to narrow field types indexed w/ const assertions #45965

bsuth opened this issue Sep 20, 2021 · 3 comments · Fixed by #45974

Comments

@bsuth
Copy link

bsuth commented Sep 20, 2021

Bug Report

🔎 Search Terms

const assertion
const narrow
assertion narrow

🕗 Version & Regression Information

First seen in 4.1.2, reproduced in 4.4.3 and 4.5.0-dev.20210919.

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about "Type System Behavior", "Type Guards", "Things That Don't Work"

⏯ Playground Link

Playground link with relevant code

💻 Code

const test: { myfield?: number } = {};
const constField = 'myfield' as const;

if (test[constField]) {
  console.log(test[constField] + 1); // Object is possibly 'undefined'
  console.log(test.myfield + 1); // Object is possibly 'undefined'
}

🙁 Actual behavior

TypeScript is not able to narrow test[constField] from undefined|number to number

🙂 Expected behavior

TypeScript infers that test[constField] is simply number in the if block

@IllusionMH
Copy link
Contributor

Looks like duplicate of #44899 and linked issues.

@easyrider
Copy link

This is also possibly a #10530 duplicate - an issue that appears frequently since 2016, the solution was already proposed as a PR but was declined.

@bsuth
Copy link
Author

bsuth commented Sep 21, 2021

indeed this seems to be a duplicate, closing in favor of #10530

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants