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

Object with optional properties is not type narrowed #44866

Closed
bartenra opened this issue Jul 2, 2021 · 1 comment
Closed

Object with optional properties is not type narrowed #44866

bartenra opened this issue Jul 2, 2021 · 1 comment

Comments

@bartenra
Copy link

bartenra commented Jul 2, 2021

Bug Report

πŸ”Ž Search Terms

Type narrowing optional property

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about type narrowing.

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

type Slot = { id?: string }

function needsId(slot: { id: string }) {
}

function test(slot: Slot) {
  if (slot.id) {
    needsId(slot)
  }
}

πŸ™ Actual behavior

The compiler complains that on the line where needsId is called, string | undefined cannot be assigned to string.

πŸ™‚ Expected behavior

Inside the if-statement, the Typescript compiler knows that slot.id is a string. I expect slot to be narrowed to Slot & { id: string } inside the if-statement, so that needsId(slot) is a valid call.

@MartinJohns
Copy link
Contributor

MartinJohns commented Jul 2, 2021

Quoting @jack-williams:

Type guards do not propagate type narrowings to parent objects. The narrowing is only applied upon access of the narrowed property which is why the destructing function works, but the reference function does not. Narrowing the parent would involve synthesizing new types which would be expensive. More detail in this comment.

Duplicate of #42384.

@bartenra bartenra closed this as completed Jul 2, 2021
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

No branches or pull requests

2 participants