user1906
user1906

Reputation: 2340

Typescript type enforcement

I'm new to Typescript, and I'm a bit puzzled about why this code compiles correctly. images is an Array of strings, yet this.data is assigned and object where images is an Object.

declare type vd = {
    images: Array<string>;
}

class mytest {
   data: vd;

   constructor() {
     let obj = ['hello!', 'bye'];
     this.data = { images: { ...obj } };
     console.log(this.data.images);
   }
}

As expected, this is printed on the console:

Object 0: "hello!" 1: "bye"

Changing the curly braces for regular braces, prints the following:

Array(2) 0: "hello!" 1:"bye" length: 2

Why isn't the compiler complaining on the assignment of this.data in the first case?

Upvotes: 3

Views: 282

Answers (1)

artem
artem

Reputation: 51629

In javascript and typescript, arrays are objects, so with you obj variable initialized as array, this pointless operation is valid and allowed - as Aluan Haddad said in the comment, you can spread array (which is an object) into an object:

    {...obj}

To reveal what type it produces, you can add this pointless assignment and watch the error message:

const r: void = { ...obj }

Type '{ [n: number]: string; length: number; toString(): string; toLocaleString(): string; push(...item...' is not assignable to type 'void'.

See, as a result of spread, the type of {...obj} looks just like an array, it has indexable by number signature, and it has all properties and methods that array has, so, by TypeScript structural compatibility rules, it's assignable to an array - that's why there is no error in your code.

This is different from what you would get in javascript at runtime. Non-enumerable properties of the array would not be copied to an object, and the result would have only two properties that come from array indexes - "1" and "2".

This is a shortcoming of TypeScript type system - there is no way to account for non-enumerable properties, they are treated as if they were enumerable like all other properties. If there were, this assignment would have produced an error.

Upvotes: 4

Related Questions