Skip to content

Unexpected behavior of property type guard #54031

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
doronguttman opened this issue Apr 26, 2023 · 3 comments
Closed

Unexpected behavior of property type guard #54031

doronguttman opened this issue Apr 26, 2023 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@doronguttman
Copy link

Bug Report

πŸ”Ž Search Terms

type guard property

πŸ•— Version & Regression Information

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

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

interface X {
    foo?: string;
}

declare const x: X;

const a: 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) {
    const b: string = x.foo;
    const c: 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.

@fatcerberus
Copy link

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.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Apr 26, 2023
@microsoft-github-policy-service

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

1 similar comment
@microsoft-github-policy-service

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

3 participants