From 9fbdcda5b17ca3e584dfc8394686279c419c077a Mon Sep 17 00:00:00 2001 From: HosokawaR <45098934+HosokawaR@users.noreply.github.com> Date: Wed, 27 Apr 2022 18:56:38 +0900 Subject: [PATCH] Print `as` instead of `:` for `babel-ts` parser (#12706) Co-authored-by: fisker Cheung --- changelog_unreleased/typescript/12706.md | 13 +++++++++++++ src/language-js/print/misc.js | 5 +++++ .../typescript/as/__snapshots__/jsfmt.spec.js.snap | 14 ++++++++++++++ tests/format/typescript/as/array-pattern.ts | 1 + 4 files changed, 33 insertions(+) create mode 100644 changelog_unreleased/typescript/12706.md create mode 100644 tests/format/typescript/as/array-pattern.ts diff --git a/changelog_unreleased/typescript/12706.md b/changelog_unreleased/typescript/12706.md new file mode 100644 index 000000000..8c21a8d0e --- /dev/null +++ b/changelog_unreleased/typescript/12706.md @@ -0,0 +1,13 @@ +#### Print `as` instead of `:` for `babel-ts` parser (#12706 by @HosokawaR) + + +```tsx +// Input +[x as any] = x; + +// Prettier stable +[x: any] = x; + +// Prettier main +[x as any] = x; +``` diff --git a/src/language-js/print/misc.js b/src/language-js/print/misc.js index 3d5a7d0f8..81514bee0 100644 --- a/src/language-js/print/misc.js +++ b/src/language-js/print/misc.js @@ -55,6 +55,11 @@ function printTypeAnnotation(path, options, print) { const parentNode = path.getParentNode(); + // Workaround for https://github.com/babel/babel/issues/14498 + if (parentNode.type === "ArrayPattern" && options.parser === "babel-ts") { + return [" as ", print("typeAnnotation")]; + } + const isFunctionDeclarationIdentifier = parentNode.type === "DeclareFunction" && parentNode.id === node; diff --git a/tests/format/typescript/as/__snapshots__/jsfmt.spec.js.snap b/tests/format/typescript/as/__snapshots__/jsfmt.spec.js.snap index bdfd027ec..27a91f18a 100644 --- a/tests/format/typescript/as/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/typescript/as/__snapshots__/jsfmt.spec.js.snap @@ -1,5 +1,19 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP +exports[`array-pattern.ts format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +[x as any] = x; + +=====================================output===================================== +[x as any] = x; + +================================================================================ +`; + exports[`as.ts format 1`] = ` ====================================options===================================== parsers: ["typescript"] diff --git a/tests/format/typescript/as/array-pattern.ts b/tests/format/typescript/as/array-pattern.ts new file mode 100644 index 000000000..364250a98 --- /dev/null +++ b/tests/format/typescript/as/array-pattern.ts @@ -0,0 +1 @@ +[x as any] = x;