tjugg
tjugg

Reputation: 3367

Typescript type restrictions behavior

I'm relatively new to the Typescript world, and I'm just working on a test app to get my self used to it. So I have this weird (?) issue with type restriction 'not working'.

I have an array defined in a class like member field this:

listings: Array<ICryptListingItem> = [];

And the interface is:

export interface ICryptListingItem {
  name: string;
  something: number;
}

Why is the compiler fine with doing:

  this.listings = listings.data.map((listing) => {
      return {
        name: listing.name
      }
    });

The objects returned from listings.data.map is not implementing the interface the array has as it's type? What am I not getting here?

Thanks in advance.

Upvotes: 1

Views: 150

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221392

TypeScript does handle this automatically; your code sample is missing some information. For example:

export interface ICryptListingItem {
    name: string;
    something: number;
}

class MyThing {
    listings: Array<ICryptListingItem> = [];

    doSomething() {
        const listings = {
            data: [
                { name: "the keeper" },
                { name: "the seeker" }
            ]
        };

        // Error here, as expected
        this.listings = listings.data.map((listing) => {
            return {
                name: listing.name
            }
        });
    }
}

Probably the type of either listings or listings.data is any, so the result of the map call is also any; any is then always an allowed type to assign to this.listings.

Upvotes: 1

Related Questions