/** * Uses TypeScript's built-in `Extract` utility type to create a new type * by extracting all members from a union type (T) that are assignable to another type (U). * This is useful for filtering union types based on their underlying structure. */ type AllTypes = string | number | boolean | Function | { id: number, name: string } | null; // Extract only string types type StringOnly = Extract; // Expected: string const myString: StringOnly = 'hello'; // const anotherString: StringOnly = 123; // Type Error // Extract only number types type NumberOnly = Extract; // Expected: number const myNumber: NumberOnly = 42; // Extract only function types type FunctionOnly = Extract; // Expected: Function const myFunction: FunctionOnly = () => console.log('I am a function'); // Extract only object types (excluding null) type ObjectOnly = Extract; // Expected: { id: number, name: string } const myObject: ObjectOnly = { id: 1, name: 'TS' }; // const invalidObject: ObjectOnly = null; // Type Error: Type 'null' is not assignable to type 'ObjectOnly'. // Extract all primitive types type Primitives = Extract; // Expected: string | number | boolean | null const myPrimitive: Primitives = true; const anotherPrimitive: Primitives = null; // Demonstrating with a more complex union and interface interface Car { brand: string; } interface Bike { wheels: number; } interface Plane { engines: number; } type Vehicle = Car | Bike | Plane | string; type OnlyCars = Extract; // Expected: Car const myCar: OnlyCars = { brand: 'Tesla' }; type OnlyNonStrings = Exclude; // Expected: Car | Bike | Plane const myBike: OnlyNonStrings = { wheels: 2 }; console.log('--- Extract Union Members Demo ---'); console.log(`StringOnly: ${myString} (type: ${typeof myString})`); console.log(`NumberOnly: ${myNumber} (type: ${typeof myNumber})`); myFunction(); console.log(`ObjectOnly: ${JSON.stringify(myObject)} (type: ${typeof myObject})`); console.log(`Primitives: ${myPrimitive} (type: ${typeof myPrimitive})`); console.log(`OnlyCars: ${JSON.stringify(myCar)}`);