Typescript: Destructuring object polyfill isn't equivalent to new JS

Created on 20 May 2019  路  2Comments  路  Source: microsoft/TypeScript


TypeScript Version: 3.4.0-dev.201xxxxx


Search Terms: Destructuring object Polyfill assign

Code

const k = { o: 1, b: 2 };
const o = {
    o: 3,
    ...k,
    b: k.o++,
};

console.log(o)

Compiles to

var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var k = { o: 1, b: 2 };
var o = __assign({ o: 3 }, k, { b: k.o++ });
console.log(o);

Compiling to __assign({ o: 3 }, k, { b: k.o++ }) is not equivalent to the order in which the JS would execute. What would be equivalent is __assign(__assign({ o: 3 }, k), { b: k.o++ })

Expected behavior: { o: 1, b: 1 }

Actual behavior: {o: 2, b: 1}

Playground Link: https://www.typescriptlang.org/play/#src=const%20k%20%3D%20%7B%20o%3A%201%2C%20b%3A%202%20%7D%3B%0Aconst%20o%20%3D%20%7B%0A%09o%3A%203%2C%0A%09...k%2C%0A%09b%3A%20k.o%2B%2B%2C%0A%7D%3B%0A%0Aconsole.log(o)

Related Issues:

Bug

Most helpful comment

This is also an issue if the spread object somehow mutates a binding of another spread object:

const k = { a: 1, get b() { l = { z: 9 }; return 2; } };
let l = { c: 3 };
const o = { ...k, ...l };
console.log(o);

Expected: { a: 1, b: 2, z: 9 }
Actual: { a: 1, b: 2, c: 3 }

All 2 comments

FWIW Babel has the same output

This is also an issue if the spread object somehow mutates a binding of another spread object:

const k = { a: 1, get b() { l = { z: 9 }; return 2; } };
let l = { c: 3 };
const o = { ...k, ...l };
console.log(o);

Expected: { a: 1, b: 2, z: 9 }
Actual: { a: 1, b: 2, c: 3 }

Was this page helpful?
0 / 5 - 0 ratings

Related issues

CyrusNajmabadi picture CyrusNajmabadi  路  3Comments

weswigham picture weswigham  路  3Comments

dlaberge picture dlaberge  路  3Comments

kyasbal-1994 picture kyasbal-1994  路  3Comments

siddjain picture siddjain  路  3Comments