|
) TypeVariable can hold a value of either types defined
const varName = string | number;
varName
variable can be either string
type or number
type
varName = "3"; // allowed varName = 3; // allowed
&
)Creates a single new type
by combining multiple existing types
type typeAB = typeA & typeB;
typeAB
will have all properties from both typeA
and typeB
.Union
vs Intersection
If a union
is an OR
, then an intersection
is an AND
When you have multiple type intersections like this example:
type MultipleIntersection = TypeA & TypeB & TypeC;
And intersection has a property that is defined multiple times of different types, you will get an error
interface TypeA { id: number; name: string; } interface TypeB { id: string; age: number; } // conflicting `id` property, will error type ErroringIntersection = TypeA & TypeB
Order of type intersection does not matter
type typeAB = typeA & typeB; type typeBA = typeB & typeA;
Type typeAB
and typeBA
have the same properties.