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

Inconsistent Errors on conditional assignment with optional object properties #46276

Closed
mkaraula opened this issue Oct 8, 2021 · 3 comments
Closed
Labels
Duplicate An existing issue was already created

Comments

@mkaraula
Copy link

mkaraula commented Oct 8, 2021

Bug Report

πŸ”Ž Search Terms

  • object
  • optional properties
  • undefined
  • conditional assignment

πŸ•— Version & Regression Information

  • This is the behavior in every version I have tried

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

type Foo = { one: boolean | undefined }
type Bar = {one: boolean}

const foo: Foo = {one: undefined};


const barOne: Bar = foo.one !== undefined ? foo : { one: true };

const barTwo: Bar = foo.one !== undefined ? {one: foo.one} : { one: true }

πŸ™ Actual behavior

The assignment for barOne throws an error but the assignment for barTwo does not.

πŸ™‚ Expected behavior

I was expecting that either both of them fail or that none of them is failing.

πŸ‘‹

Apologies if this is not a Bug but I dont get it and I could not find any explanation for this online.

I got stuck for quite a while with this Issue. My problem is that I dont understand why an conditional assignmnet like the one for barOne is failing. Then I discovered that when I do the assignment like I did for barTwo, Typescript isnt complaining.

I would expect that eiter both of them throw an error or both of them dont throw one.

@fatcerberus
Copy link

Checking the value of foo.one doesn't narrow foo. This kind of transitive narrowing only works in specific cases, e.g. discriminated unions.

@andrewbranch
Copy link
Member

I think basically a duplicate of #18758; see #38839

@andrewbranch andrewbranch added the Duplicate An existing issue was already created label Oct 11, 2021
@typescript-bot
Copy link
Collaborator

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