Skip to content

Following non-null assertion of optional field, it is still considered nullable #55409

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

Closed
orgads opened this issue Aug 17, 2023 · 2 comments
Closed

Comments

@orgads
Copy link

orgads commented Aug 17, 2023

πŸ”Ž Search Terms

"undefined is not assignable" assertion

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about common bugs

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.1.6#code/JYOwLgpgTgZghgYwgAgGIHt3IN4FgBQAkALYCeAbnFAFzIDOYUoA5gNwEC+BoksiKAISo4CJClQD8tBkxBtOBAjACuIBGGDoQyABZwQAEwA2EDOgAUAfRiZaZgJQ4u+JavWbtewyaFRzAIypaX0c8ImAYZHMAQkCoADoySih7UUIoCDBlKBB2Ii9jU0wAqns85yA

πŸ’» Code

interface Foo {
	myvar: string;
}
interface Bar {
	myvar?: string;
}

function handleFoo(_foo: Foo) {}

function handleBar(bar: Bar) {
	if (!bar.myvar)
		return;
	handleFoo(bar);
}

πŸ™ Actual behavior

Argument of type 'Bar' is not assignable to parameter of type 'Foo'.
  Types of property 'myvar' are incompatible.
    Type 'string | undefined' is not assignable to type 'string'.
      Type 'undefined' is not assignable to type 'string'.

πŸ™‚ Expected behavior

It should work, as I verified myvar is defined.

Additional information about the issue

No response

@MartinJohns
Copy link
Contributor

The field is not considered nullable, but the check does not change the parent type.

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.

Used search terms: type guard property parent

Duplicate of #42384.

@orgads
Copy link
Author

orgads commented Aug 17, 2023

Thank you.

@orgads orgads closed this as completed Aug 17, 2023
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