Add parentheses to TypeofTypeAnnotation (#14458)

This commit is contained in:
fisker Cheung authored and GitHub committed 2023-03-08 09:16:03 +08:00
1 parent 3d706379ed
commit f1b18f2319
5 files changed
+35 -21

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
#### Add parentheses for `TypeofTypeAnnotation` to improve readability (#14458 by @fisker)
<!-- prettier-ignore -->
```tsx
// Input
type A = (typeof node.children)[];
// Prettier stable
type A = typeof node.children[];
// Prettier main
type A = (typeof node.children)[];
```
+8 -7
View File
@@ -529,6 +529,14 @@ function needsParens(path, options) {
(name === "objectType" && parent.type === "TSIndexedAccessType") ||
(name === "elementType" && parent.type === "TSArrayType")
);
// Same as `TSTypeQuery`, but for Flow syntax
case "TypeofTypeAnnotation":
return (
(name === "objectType" &&
(parent.type === "IndexedAccessType" ||
parent.type === "OptionalIndexedAccessType")) ||
(name === "elementType" && parent.type === "ArrayTypeAnnotation")
);
case "ArrayTypeAnnotation":
return parent.type === "NullableTypeAnnotation";
@@ -583,13 +591,6 @@ function needsParens(path, options) {
case "OptionalIndexedAccessType":
return name === "objectType" && parent.type === "IndexedAccessType";
case "TypeofTypeAnnotation":
return (
name === "objectType" &&
(parent.type === "IndexedAccessType" ||
parent.type === "OptionalIndexedAccessType")
);
case "StringLiteral":
case "NumericLiteral":
case "Literal":
@@ -2,20 +2,20 @@
exports[`typeof.ts format 1`] = `
====================================options=====================================
parsers: ["typescript"]
parsers: ["typescript", "flow"]
printWidth: 80
| printWidth
=====================================input======================================
a as (typeof node.children)[number]
a as (typeof node.children)[]
a as ((typeof node.children)[number])[]
a as number[(typeof node.children)]
type A = (typeof node.children)[number];
type B = (typeof node.children)[];
type C = ((typeof node.children)[number])[];
type D = number[(typeof node.children)];
=====================================output=====================================
a as (typeof node.children)[number];
a as (typeof node.children)[];
a as (typeof node.children)[number][];
a as number[typeof node.children];
type A = (typeof node.children)[number];
type B = (typeof node.children)[];
type C = (typeof node.children)[number][];
type D = number[typeof node.children];
================================================================================
`;
+1 -1
View File
@@ -1 +1 @@
run_spec(__dirname, ["typescript"]);
run_spec(__dirname, ["typescript", "flow"]);
+4 -4
View File
@@ -1,4 +1,4 @@
a as (typeof node.children)[number]
a as (typeof node.children)[]
a as ((typeof node.children)[number])[]
a as number[(typeof node.children)]
type A = (typeof node.children)[number];
type B = (typeof node.children)[];
type C = ((typeof node.children)[number])[];
type D = number[(typeof node.children)];