Explain the concept of Union and Intersection types
Answer
- Union (
|
): Represents values that can be one of several types. - Intersection (
&
): Combines multiple types into one.
// Union
let id: string | number;
id = "abc"; // Valid
id = 123; // Valid
// Intersection
interface User {
name: string;
}
interface Admin {
admin: boolean;
}
type AdminUser = User & Admin;
const admin: AdminUser = { name: "John", admin: true };