Destructing an array inside an object

Create a simple array and destroy it inside the (empty) object:

const foo: Array<number> = [1, 2, 3, 4];
const bar: Array<number> = {...foo};

Should I check the type here? barnot like an array to me. The editor does not complain at all and treats it baras an array type, although I can easily check at runtime that it is not.

Edit

Playing it easily on a TypeScript playground.

+4
source share
2 answers

This seems like a known issue, since the {...foo}destructuring is compiled into Object.assign({}, foo)and Object.assign()declared as

assign<T, U>(target: T, source: U): T & U;

therefore, when the second argument is an array, the result is compatible with the type of the array.

, , Object.assign:

, PR , , , Object.assign :

assign (target: T, source: U): {... T,... U}

, , length, ,

const p: Array<number> = {};

// Type '{}' is not assignable to type 'number[]'.
// Property 'length' is missing in type '{}'.
+2

javascript:

var __assign = (this && this.__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;
};
var foo = [1, 2, 3, 4];
var bar = __assign({}, foo);

, , , typescript , , , .

, :

const foo1: Array<number> = [1, 2, 3, 4];
const bar1: Array<number> = [...foo1];

, , .

+3

Source: https://habr.com/ru/post/1672815/


All Articles