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
interfaceX{foo?: string;}declareconstx: X;consta: string=x.foo;// ^ expected error: Type 'string | undefined' is not assignable to type 'string'.// Type 'undefined' is not assignable to type 'string'.(2322)if(x.foo){constb: string=x.foo;constc: X&{foo: string;}=x;// ^ unexpected error: Type 'X' is not assignable to type 'X & { foo: string; }'.// Property 'foo' is missing in type 'X' but required in type '{ foo: string; }'.(2322)console.log(b,c);}
π Actual behavior
A type has an optional property. Using an if assertion statement, TypeScript knows to narrow the optional property when referring to the property itself, but does not know to "narrow" the object as having the property defined.
π Expected behavior
Inside the if assertion, I would expect TypeScript to know that the object has the property defined.
The text was updated successfully, but these errors were encountered:
Duplicate of #42384, #31755, and probably a bunch of others. This is a manifestation of a very long-standing limitation.
Interestingly, this very issue is a good case in point for the concern raised here #31755 (comment); it would quickly lead to the compiler synthesizing a bunch of intersections, even from known starting types, which would likely be a performance/memory-pressure issue.
Bug Report
π Search Terms
type guard property
π Version & Regression Information
β― Playground Link
Playground link with relevant code
π» Code
π Actual behavior
A type has an optional property. Using an
if
assertion statement, TypeScript knows to narrow the optional property when referring to the property itself, but does not know to "narrow" the object as having the property defined.π Expected behavior
Inside the
if
assertion, I would expect TypeScript to know that the object has the property defined.The text was updated successfully, but these errors were encountered: