In TypeScript, union types and intersection types are ways to combine multiple types to create new types with specific characteristics.
Union Types (|):
A union type allows a variable to have one of several types. It is represented using the | symbol.
// Union type
type MyType = string | number;
let value: MyType;
value = "Hello"; // Valid
value = 42; // Valid
// value = true; // Error: Type 'boolean' is not assignable to type 'string | number'.
Intersection Types (&):
An intersection type combines multiple types into one, allowing an object to have all properties from each type. It is represented using the & symbol.
// Intersection type
type Point2D = { x: number; y: number };
type Point3D = { z: number };
type Point = Point2D & Point3D;
const point: Point = { x: 1, y: 2, z: 3 };
Union Types vs. Intersection Types:
Union Types:
Represents a value that can be one of several types.
Uses the | symbol.
The value can be of any type in the union.
Intersection Types:
Represents a value that has all properties of multiple types.
Uses the & symbol.
The value must have all the properties of all types in the intersection.
Example of Using Both:
type A = { foo: number };
type B = { bar: string };
// Union type
type UnionType = A | B;
let unionValue: UnionType;
unionValue = { foo: 42 }; // Valid
unionValue = { bar: "hello" }; // Valid
// unionValue = { foo: 42, bar: "hello" }; // Error: Object literal may only specify known properties, and 'bar' does not exist in type 'A'.
// Intersection type
type IntersectionType = A & B;
let intersectionValue: IntersectionType;
intersectionValue = { foo: 42, bar: "hello" }; // Valid
// intersectionValue = { foo: 42 }; // Error: Property 'bar' is missing in type '{ foo: number; }' but required in type 'B'.