из документации машинописного текста я знаю, что «&» означает «Типы пересечений» и «|» представляет «Типы Союза». Но мне интересно, в чем разница со следующим примером:
type Type1 = number | boolean;
type Type2 = number & boolean;
Из официального документа Typescript:
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.
Было бы не так актуально объяснять это примитивными типами, такими как число или логическое значение, но представьте, что у вас есть два таких класса:
export class Toto {
FirstName: string;
LastName: string;
}
export class Tata {
PhoneNumber: number;
}
Если вы пишете type Type1 = Toto | Tata;
, то ваш Type1 будет либо экземпляром Toto, либо экземпляром Tata, но не оба.
Но если вы напишете type Type2 = Toto & Tata;
, тогда ваш Type2 будет типом, имеющим все атрибуты Toto и Tata (FirstName, LastName и PhoneNumber).
См. Более подробную информацию в док, там это довольно хорошо объяснено.