Union & Intersection types
class
Union (|) means "one of these types"; Intersection (&) means "all of these types combined".
Syntax
type A = TypeX | TypeY type B = TypeX & TypeY
Example
javascript
// Union — either type
type StringOrNumber = string | number;
function format(val: StringOrNumber): string {
return typeof val === 'string' ? val : val.toString();
}
// Literal union — finite set of values
type Direction = 'north' | 'south' | 'east' | 'west';
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
// Intersection — combine types
type Serializable = { serialize(): string };
type Loggable = { log(): void };
type LoggableUser = User & Serializable & Loggable;