Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix to add parentheses for TSTypeQuery in some case #14042

Merged
merged 13 commits into from Dec 30, 2022
22 changes: 22 additions & 0 deletions changelog_unreleased/typescript/14042.md
@@ -0,0 +1,22 @@
#### Add parentheses for TSTypeQuery to improve readability (#14042 by @onishi-kohei)

<!-- prettier-ignore -->
```tsx
// Input
a as (typeof node.children)[number]
a as (typeof node.children)[]
a as ((typeof node.children)[number])[]
a as number[(typeof node.children)]

// Prettier stable
a as typeof node.children[number];
a as typeof node.children[];
a as typeof node.children[number][];
a as number[typeof node.children];

// Prettier main
a as (typeof node.children)[number];
a as (typeof node.children)[];
a as (typeof node.children)[number][];
a as number[typeof node.children];
```
6 changes: 5 additions & 1 deletion src/language-js/needs-parens.js
Expand Up @@ -456,7 +456,11 @@ function needsParens(path, options) {
(parent.type === "TSTypeAnnotation" &&
path.getParentNode(1).type.startsWith("TSJSDoc"))
);

case "TSTypeQuery":
return (
(name === "objectType" && parent.type === "TSIndexedAccessType") ||
(name === "elementType" && parent.type === "TSArrayType")
);
case "ArrayTypeAnnotation":
return parent.type === "NullableTypeAnnotation";

Expand Down
21 changes: 21 additions & 0 deletions tests/format/typescript/typeof/__snapshots__/jsfmt.spec.js.snap
@@ -0,0 +1,21 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`typeof.ts format 1`] = `
====================================options=====================================
parsers: ["typescript"]
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)]

=====================================output=====================================
a as (typeof node.children)[number];
a as (typeof node.children)[];
a as (typeof node.children)[number][];
a as number[typeof node.children];

================================================================================
`;
1 change: 1 addition & 0 deletions tests/format/typescript/typeof/jsfmt.spec.js
@@ -0,0 +1 @@
run_spec(__dirname, ["typescript"]);
4 changes: 4 additions & 0 deletions tests/format/typescript/typeof/typeof.ts
@@ -0,0 +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)]