from typescript's docs, I know '&' means 'Intersection Types' and '|' represents 'Union Types'. But I wonder what's the differences with following example:
type Type1 = number | boolean;
type Type2 = number & boolean;
from typescript's docs, I know '&' means 'Intersection Types' and '|' represents 'Union Types'. But I wonder what's the differences with following example:
type Type1 = number | boolean;
type Type2 = number & boolean;
From the official Typescript doc :
A union type describes a value that can be one of several types. We use the vertical bar (|) to separate each type, so number | string | boolean is the type of a value that can be a number, a string, or a boolean.
An intersection type combines multiple types into one. This allows you to add together existing types to get a single type that has all the features you need. For example, Person & Serializable & Loggable is a Person and Serializable and Loggable. That means an object of this type will have all members of all three types.
It would not be so relevant to explain it with primitive types like number or boolean but imagine having two classes like this :
export class Toto {
FirstName: string;
LastName: string;
}
export class Tata {
PhoneNumber: number;
}
If you write type Type1 = Toto | Tata; then your Type1 will be either a Toto instance or a Tata instance but not both.
But if you write type Type2 = Toto & Tata; then your Type2 will be a type having all Toto and Tata attributes (FirstName, LastName and PhoneNumber).
See the doc for more details, it is pretty well explained there.