Search code examples
typescriptgenericstypescript-genericssubtypeintersection-types

Typescript - Could Intersection type be considered as Subtype of the type that is contained in that intersection?


I have a question that relates to generic type and subtype concepts in Typescript. But after spending a while reading Typescript official document I still haven't found the answer. My question is that: Could Intersection type be considered as subtype of the type that create the intersection.

I have the following type:

type Dog = { color:string}
type Cat = { gender:boolean}
type Fish = { weigh: number}

type Dog_Cat_Fish = Dog & Cat & Fish;
type Dog_Cat = Dog & Cat;

Can I state that:

  • Dog_Cat_Fish is subtype of Cat (1)
  • Dog_Cat_Fish is subtype of Dog_Cat (2)
  • T & U is subtype of T (3)
  • T & U & V is subtype of T & V (4)

Where T,V and U are *type variables ( generic types).

Thank you for considering my stupid question.


Solution

  • The answer to all 4 of your bullet points is yes.

    This is the case even when the members of your types are incompatible

    type Dog = { color:string }
    type Cat = { color:boolean }
    type Dog_Cat = Dog & Cat
    

    No values of this type can exist, however it is a subtype of both Dog and Cat. It is equivalent to never, but might not be displayed as such by tools