From e6bf63ebe84e7d8c0aa2b2594d28247258a242fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hu=C3=A1ng=20J=C3=B9nli=C3=A0ng?= Date: Fri, 8 Nov 2019 22:22:03 -0500 Subject: [PATCH] reimplement asserts-this --- .../src/plugins/typescript/index.js | 43 +++++++++---------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/packages/babel-parser/src/plugins/typescript/index.js b/packages/babel-parser/src/plugins/typescript/index.js index 5af5fe51a871..448c62c94abe 100644 --- a/packages/babel-parser/src/plugins/typescript/index.js +++ b/packages/babel-parser/src/plugins/typescript/index.js @@ -940,22 +940,26 @@ export default (superClass: Class): Class => this.tsParseTypePredicateAsserts.bind(this), ); - let typePredicateVariable = null; - if (this.tsIsIdentifier()) { - // TypePredicate - // : foo is type - typePredicateVariable = this.tsTryParse( - this.tsParseTypePredicatePrefix.bind(this), - ); - } else if (asserts && this.match(tt._this)) { - // When asserts is false, thisKeyword is handled by tsParseNonArraytype - // TypePredicate - // : this is type - typePredicateVariable = this.tsTryParse( - this.tsParseThisTypeOrThisTypePredicate.bind(this), - ); + if (asserts && this.match(tt._this)) { + // When asserts is false, thisKeyword is handled by tsParseNonArrayType + const node = this.startNodeAtNode(t); + // : asserts this is type + let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate(); + // if it turns out to be a `TSThisType`, wrap it with `TSTypePredicate` + // : asserts this + if (thisTypePredicate.type === "TSThisType") { + node.parameterName = thisTypePredicate; + node.asserts = true; + thisTypePredicate = this.finishNode(node, "TSTypePredicate"); + } + t.typeAnnotation = thisTypePredicate; + return this.finishNode(t, "TSTypeAnnotation"); } + const typePredicateVariable = + this.tsIsIdentifier() && + this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this)); + if (!typePredicateVariable) { if (!asserts) { // : type @@ -963,19 +967,14 @@ export default (superClass: Class): Class => } const node = this.startNodeAtNode(t); - if (this.match(tt._this)) { - // : asserts this - node.parameterName = this.tsParseThisTypeNode(); - } else { - // : asserts foo - node.parameterName = this.parseIdentifier(); - } + // : asserts foo + node.parameterName = this.parseIdentifier(); node.asserts = asserts; t.typeAnnotation = this.finishNode(node, "TSTypePredicate"); return this.finishNode(t, "TSTypeAnnotation"); } - // : asserts TypePredicate + // : asserts foo is type const type = this.tsParseTypeAnnotation(/* eatColon */ false); const node = this.startNodeAtNode(t); node.parameterName = typePredicateVariable;