diff --git a/changelog_unreleased/javascript/15915.md b/changelog_unreleased/javascript/15915.md new file mode 100644 index 000000000..b493ac1b2 --- /dev/null +++ b/changelog_unreleased/javascript/15915.md @@ -0,0 +1,14 @@ +#### Fix formatting error on member chain (#15915 by @sosukesuzuki) + + +```jsx +// Input +test().test2().test2(thing?.something); + +// Prettier stable +TypeError: Cannot read properties of undefined (reading 'type') + +// Prettier main +test().test2().test2(thing?.something); + +``` diff --git a/src/language-js/utils/index.js b/src/language-js/utils/index.js index b3bfe1646..7ba6692b7 100644 --- a/src/language-js/utils/index.js +++ b/src/language-js/utils/index.js @@ -405,6 +405,16 @@ function isTestCall(node, parent) { /** @return {(node: Node) => boolean} */ const skipChainExpression = (fn) => (node) => { if (node?.type === "ChainExpression") { + // @ts-expect-error + if (!node.object) { + // @ts-expect-error + node.object = node.expression.object; + } + // @ts-expect-error + if (!node.property) { + // @ts-expect-error + node.property = node.expression.property; + } node = node.expression; } diff --git a/tests/format/js/chain-expression/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/chain-expression/__snapshots__/jsfmt.spec.js.snap index 4bd0c7234..e34333448 100644 --- a/tests/format/js/chain-expression/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/js/chain-expression/__snapshots__/jsfmt.spec.js.snap @@ -81,6 +81,22 @@ logger.log( ================================================================================ `; +exports[`issue-15912.js format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript", "flow"] +printWidth: 80 + | printWidth +=====================================input====================================== +test() + .test2() + .test2(thing?.something); + +=====================================output===================================== +test().test2().test2(thing?.something); + +================================================================================ +`; + exports[`test.js format 1`] = ` ====================================options===================================== parsers: ["babel", "typescript", "flow"] diff --git a/tests/format/js/chain-expression/issue-15912.js b/tests/format/js/chain-expression/issue-15912.js new file mode 100644 index 000000000..19a6fd6a8 --- /dev/null +++ b/tests/format/js/chain-expression/issue-15912.js @@ -0,0 +1,3 @@ +test() + .test2() + .test2(thing?.something);