[ts] Add support for template interpolations in types (#12131)

Co-authored-by: Brian Ng <bng412@gmail.com>
This commit is contained in:
Nicolò Ribaudo
2020-10-14 20:15:42 +02:00
committed by GitHub
parent 9f40d6fcd0
commit 3fd963fdc8
10 changed files with 106 additions and 19 deletions

View File

@@ -1608,7 +1608,7 @@ export default class ExpressionParser extends LValParser {
node.quasis = [curElt];
while (!curElt.tail) {
this.expect(tt.dollarBraceL);
node.expressions.push(this.parseExpression());
node.expressions.push(this.parseTemplateSubstitution());
this.expect(tt.braceR);
node.quasis.push((curElt = this.parseTemplateElement(isTagged)));
}
@@ -1616,6 +1616,11 @@ export default class ExpressionParser extends LValParser {
return this.finishNode(node, "TemplateLiteral");
}
// This is overwritten by the TypeScript plugin to parse template types
parseTemplateSubstitution(): N.Expression {
return this.parseExpression();
}
// Parse an object literal, binding pattern, or record.
parseObjectLike<T: N.ObjectPattern | N.ObjectExpression>(

View File

@@ -94,8 +94,6 @@ const TSErrors = Object.freeze({
"Private elements cannot have the 'abstract' modifier.",
PrivateElementHasAccessibility:
"Private elements cannot have an accessibility modifier ('%0')",
TemplateTypeHasSubstitution:
"Template literal types cannot have any substitution",
TypeAnnotationAfterAssign:
"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
UnexpectedParameterModifier:
@@ -774,17 +772,15 @@ export default (superClass: Class<Parser>): Class<Parser> =>
tsParseTemplateLiteralType(): N.TsType {
const node: N.TsLiteralType = this.startNode();
const templateNode = this.parseTemplate(false);
if (templateNode.expressions.length > 0) {
this.raise(
templateNode.expressions[0].start,
TSErrors.TemplateTypeHasSubstitution,
);
}
node.literal = templateNode;
node.literal = this.parseTemplate(false);
return this.finishNode(node, "TSLiteralType");
}
parseTemplateSubstitution(): N.TsType {
if (this.state.inType) return this.tsParseType();
return super.parseTemplateSubstitution();
}
tsParseThisTypeOrThisTypePredicate(): N.TsThisType | N.TsTypePredicate {
const thisKeyword = this.tsParseThisTypeNode();
if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {