为何TypeScript 2.7.2在target为es2017时将对象展开编译为Object.assign?
Object.assign with target: "es2017"? Great question! Let's break down exactly what's going on here:
Object spread in literals is an ES2018 feature, not ES6/ES2017
A common mix-up: array spread ([...array]) was added in ES6 (ES2015), but the object spread syntax for literals ({...object}) didn't become official ECMAScript standard until ES2018. Even though it feels like a core ES6 feature, it's actually a later addition.TypeScript's
targetoption enforces version compatibility
When you settarget: "es2017"in yourtsconfig.json, TypeScript guarantees that all compiled code works with ES2017 and earlier versions. Since object spread isn't part of the ES2017 spec, the compiler translates it to the equivalent ES2017-compatible code:Object.assign({}, data). This achieves the same result—copying enumerable properties fromdatainto a new object—while staying compatible with older environments.ESNextpreserves cutting-edge syntax
Usingtarget: "ESNext"tells TypeScript to emit code using the latest ECMAScript features it supports (including newly standardized or even proposal-stage features). In your case, this means keeping the object spread syntax exactly as you wrote it, instead of downleveling it to older syntax.
For your TypeScript 2.7.2 setup, if you want to retain the object spread syntax while targeting a formal standard version, you can switch target to "es2018" instead of "es2017". TypeScript 2.7 already supports ES2018 features like object spread, so this will emit the spread syntax directly without translation.
内容的提问来源于stack exchange,提问作者jmls

