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:
@@ -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");
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user