Union types

Union types allow a variable or parameter to accept multiple types. In this example, the add function uses any type with runtime type checking to handle both numbers and strings, demonstrating how union types can provide flexibility while maintaining type safety through validation.

function add(a: any, b: any) {
    if (typeof a === 'number' && typeof b === 'number') {
        return a + b;
    }
    if (typeof a === 'string' && typeof b === 'string') {
        return a.concat(b);
    }
    throw new Error('Parameters must be numbers or strings');
}
3
console.log(add(1, 2));
3
console.log(add("Hello", "Moon"));
HelloMoon
console.log(add(true, false));
Error: Parameters must be numbers or strings
Stack trace:
Error: Parameters must be numbers or strings
    at add (<anonymous>:8:9)
    at <anonymous>:1:34