Skip to content
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

Allow switch statement type guards (need help..) #2230

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4853,6 +4853,13 @@ module ts {
narrowedType = narrowType(type, (<ConditionalExpression>node).condition, /*assumeTrue*/ child === (<ConditionalExpression>node).whenTrue);
}
break;
case SyntaxKind.CaseClause:
// In a case clause of a switch statement using typeof
var parent = (<CaseClause>node).parent;
if((<SwitchStatement>parent).expression.kind === SyntaxKind.TypeOfExpression){
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Space after if.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make sure the parent is guaranteed to be a switch statement. It is possible that the parser lets through case labels that are not parented by a switch. Please add either an assert or a bailout condition.

narrowedType = checkExpression((<TypeOfExpression>(<CaseClause>node).expression).text);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not quite correct. You essentially need to take narrowTypeByEquality, and factor out the part that that deals with typeof, so you can access that part here. You need to check that the node.expression is a StringLiteral, and then cast it to a LiteralExpression to get the text. The TypeOfExpression in this case would be parent.expression.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As you'll see in your build results, you got

src/compiler/checker.ts(4860,114): error TS2339: Property 'text' does not exist on type 'TypeOfExpression'.

}
break;
case SyntaxKind.BinaryExpression:
// In the right operand of an && or ||, narrow based on left operand
if (child === (<BinaryExpression>node).right) {
Expand Down