driedoezoe driedoezoe - 1 month ago 9
TypeScript Question

Is it possible to use multiple interfaces on one variable?

Lets say I have a variable:

var product:Product;


the var product uses the Product interface, but I want to add a generic property 'hide' to know in my view if the product needs to be hidden. I could add 'hide' to the Product interface, but it's not a property of the Product model so it doesnt feel right.

I could make a special interface that extends Product to have both properties, but i'm wondering if there's a more simpel way to do this, something like:

var product:Product & Hide;


Is there such a syntax?

Answer

Yes, that's exactly right and it's called Intersection Types.

So either:

interface Hidden {
    hide: boolean;
}

let product: Product & Hidden;

Or

let product: Product & { hide: boolean }