You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Search Terms: union type strictnullchecks inference
Code
interfacePerson{name: string;address: {street?: string;city: string;};}declarefunctiongetPerson(): Person;functiongetMinimalAddress(): string{constperson=getPerson();if(person.address.street){constaddress=person.address;returnaddress.street;// ERROR on this line}else{returnperson.address.city;}}
Expected behavior:
Passes type checker. Since person.address.street is either null or a string, and since there is a check on line 13 for person.address.street being truthy, we know that address.street is a string.
You can get the type checker to pass by omitting the reassignment:
$ tsc --strictnullChecks broken.ts
broken.ts(15,5): error TS2322: Type 'string | undefined' is not assignable to type'string'.
Type 'undefined' is not assignable to type'string'.
We track these guards based on the expressions used to test them; unfortunately the type checker is not implemented in a way that it actually understands that address and person.address are references to the same object. There's not a lot we can do here short of a wholesale rewrite of the type guard logic, which isn't really in the cards to fix something like this.
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.
TypeScript Version: 2.9.0-dev.20180418
Search Terms: union type strictnullchecks inference
Code
Expected behavior:
Passes type checker. Since
person.address.street
is eithernull
or a string, and since there is a check on line 13 forperson.address.street
being truthy, we know thataddress.street
is a string.You can get the type checker to pass by omitting the reassignment:
Actual behavior:
Playground Link: playground link
Related Issues:
#22635
#16069
The text was updated successfully, but these errors were encountered: