Typescript: Validate tuple type element positions (#8828)

* feat: validate the positions of rest elements and optional elements in tuple types

Adds a validation step to the parser which raises syntax errors if a rest param is not at the end of a tuple, or if a mandatory param follows an optional parameter

* Fix spread after optional case; add test case
This commit is contained in:
Retsam
2018-11-06 02:19:34 -05:00
committed by Daniel Tschinder
parent e3b2c1afff
commit 2194842d11
7 changed files with 282 additions and 0 deletions

View File

@@ -507,6 +507,29 @@ export default (superClass: Class<Parser>): Class<Parser> =>
/* bracket */ true,
/* skipFirstToken */ false,
);
// Validate the elementTypes to ensure:
// No mandatory elements may follow optional elements
// If there's a rest element, it must be at the end of the tuple
let seenOptionalElement = false;
node.elementTypes.forEach((elementNode, i) => {
if (elementNode.type === "TSRestType") {
if (i !== node.elementTypes.length - 1) {
this.raise(
elementNode.start,
"A rest element must be last in a tuple type.",
);
}
} else if (elementNode.type === "TSOptionalType") {
seenOptionalElement = true;
} else if (seenOptionalElement) {
this.raise(
elementNode.start,
"A required element cannot follow an optional element.",
);
}
});
return this.finishNode(node, "TSTupleType");
}