diff --git a/changelog_unreleased/javascript/pr-8160.md b/changelog_unreleased/javascript/pr-8160.md new file mode 100644 index 000000000..5cebb6ea7 --- /dev/null +++ b/changelog_unreleased/javascript/pr-8160.md @@ -0,0 +1,20 @@ +#### Keep object key with escape sequence as it is ([#8160](https://github.com/prettier/prettier/pull/8160) by [@fisker](https://github.com/fisker)) + + +```js +// Input +const a = { + "\u2139": 'why "\\u2139" converted to "i"?', +}; + +// Prettier stable +const a = { + ℹ: 'why "\\u2139" converted to "i"?', +}; + + +// Prettier master +const a = { + "\u2139": 'why "\\u2139" is converted to "i"?', +}; +``` diff --git a/src/language-js/utils.js b/src/language-js/utils.js index e827bdf46..4ef77b9d6 100644 --- a/src/language-js/utils.js +++ b/src/language-js/utils.js @@ -729,6 +729,7 @@ function isStringPropSafeToCoerceToIdentifier(node, options) { return ( isStringLiteral(node.key) && isIdentifierName(node.key.value) && + rawText(node.key).slice(1, -1) === node.key.value && options.parser !== "json" && // With `--strictPropertyInitialization`, TS treats properties with quoted names differently than unquoted ones. // See https://github.com/microsoft/TypeScript/pull/20075 diff --git a/tests/objects/__snapshots__/jsfmt.spec.js.snap b/tests/objects/__snapshots__/jsfmt.spec.js.snap index 0cf03d454..e3887e88d 100644 --- a/tests/objects/__snapshots__/jsfmt.spec.js.snap +++ b/tests/objects/__snapshots__/jsfmt.spec.js.snap @@ -1,5 +1,33 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP +exports[`escape sequence-key.js format 1`] = ` +====================================options===================================== +parsers: ["babel"] +printWidth: 80 + | printWidth +=====================================input====================================== +// #6235 +const a = { + '\\u2139': 'why "\\\\u2139" is converted to "i"?', +}; + +const a = { + "\\x66\\x69\\x73\\x6b\\x65\\x72": "\\x66\\x69\\x73\\x6b\\x65\\x72", +}; + +=====================================output===================================== +// #6235 +const a = { + "\\u2139": 'why "\\\\u2139" is converted to "i"?', +}; + +const a = { + "\\x66\\x69\\x73\\x6b\\x65\\x72": "\\x66\\x69\\x73\\x6b\\x65\\x72", +}; + +================================================================================ +`; + exports[`expand.js format 1`] = ` ====================================options===================================== parsers: ["babel"] diff --git a/tests/objects/escape sequence-key.js b/tests/objects/escape sequence-key.js new file mode 100644 index 000000000..2772eddff --- /dev/null +++ b/tests/objects/escape sequence-key.js @@ -0,0 +1,8 @@ +// #6235 +const a = { + '\u2139': 'why "\\u2139" is converted to "i"?', +}; + +const a = { + "\x66\x69\x73\x6b\x65\x72": "\x66\x69\x73\x6b\x65\x72", +};