-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
Implement constructor check type guard #32256
Implement constructor check type guard #32256
Conversation
bar.prop1; // string | ||
bar.prop2; // number | ||
} | ||
if (bar.constructor === Foo) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
As far as I can tell, this should always be false. Right now the type get's narrowed to Bar
in the if, is this right? Or should it narrow just to Foo
?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Shouldn't it narrow to never
inside the if since Bar | boolean
can never satisfy the condition?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@fatcerberus That's a good point. I didn't think about narrowing to never
. Seems like the thing to do. I'll change this. Thanks.
src/compiler/checker.ts
Outdated
@@ -17000,6 +17006,13 @@ namespace ts { | |||
return narrowType(type, expr.right, assumeTrue); | |||
} | |||
return type; | |||
|
|||
function isConstructorAccessExpression(expr: Expression): expr is AccessExpression { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is there somewhere else I should put this or is this ok?
src/compiler/checker.ts
Outdated
return ( | ||
isPropertyAccessEntityNameExpression(expr) && idText(expr.name) === "constructor" | ||
|| isElementAccessExpression(expr) && isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor" | ||
); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not sure on the formatting of this...
Closing to reopen a fresh PR with much more detail. |
Fixes #23274
This builds on work done by @Kingwl in PR #23622 to add a new type guard checking for the
instance.constructor === Constructor
syntactic pattern to narrow the type ofinstance
.I'm making this a draft PR as there's a couple things I need some guidance on.
Thanks!