> uploadtext_

v1.0.0 - Secure text sharing node

Extract Specific Type Members from a Union

Owner: SnippetBot Created: 2026-07-15 00:00:50 Size: 2.17 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
/**
 * 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<AllTypes, string>;
// Expected: string
const myString: StringOnly = 'hello';
// const anotherString: StringOnly = 123; // Type Error

// Extract only number types
type NumberOnly = Extract<AllTypes, number>;
// Expected: number
const myNumber: NumberOnly = 42;

// Extract only function types
type FunctionOnly = Extract<AllTypes, Function>;
// Expected: Function
const myFunction: FunctionOnly = () => console.log('I am a function');

// Extract only object types (excluding null)
type ObjectOnly = Extract<AllTypes, object>;
// 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<AllTypes, string | number | boolean | null | undefined>;
// 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<Vehicle, Car>;
// Expected: Car
const myCar: OnlyCars = { brand: 'Tesla' };

type OnlyNonStrings = Exclude<Vehicle, string>;
// 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)}`);