Skip to content

Implement constructor check type guard#32256

Closed
austincummings wants to merge 1 commit into
microsoft:masterfrom
austincummings:constructorTypeGuard
Closed

Implement constructor check type guard#32256
austincummings wants to merge 1 commit into
microsoft:masterfrom
austincummings:constructorTypeGuard

Conversation

@austincummings
Copy link
Copy Markdown
Contributor

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 of instance.

I'm making this a draft PR as there's a couple things I need some guidance on.

Thanks!

bar.prop1; // string
bar.prop2; // number
}
if (bar.constructor === Foo) {
Copy link
Copy Markdown
Contributor Author

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?

Copy link
Copy Markdown

@fatcerberus fatcerberus Jul 13, 2019

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?

Copy link
Copy Markdown
Contributor Author

@austincummings austincummings Jul 13, 2019

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.

Comment thread src/compiler/checker.ts
}
return type;

function isConstructorAccessExpression(expr: Expression): expr is AccessExpression {
Copy link
Copy Markdown
Contributor Author

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?

Comment thread src/compiler/checker.ts
return (
isPropertyAccessEntityNameExpression(expr) && idText(expr.name) === "constructor"
|| isElementAccessExpression(expr) && isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor"
);
Copy link
Copy Markdown
Contributor Author

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...

@austincummings
Copy link
Copy Markdown
Contributor Author

Closing to reopen a fresh PR with much more detail.

@microsoft microsoft locked as resolved and limited conversation to collaborators Oct 21, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature Request / Proposal: constructor type guard

2 participants