Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding TypeScript Union Types

Tech 1

TypeScript Union Types

Union Types allow a variable to hold values of multiple specified types using the pipe (|) operator. The variable can only be assigned values matching the declared types.

Syntax:

type Type1 | Type2 | Type3

Basic Example

let value: string | number;
value = 12;
console.log(`Number: ${value}`);
value = "TypeScript";
console.log(`String: ${value}`);

Compiled JavaScript:

let value;
value = 12;
console.log(`Number: ${value}`);
value = "TypeScript";
console.log(`String: ${value}`);

Output:

Number: 12
String: TypeScript

Attempting to assign an invalid type causes an error:

let value: string | number;
value = true; // Type error

Function Parameters with Union Types

function display(input: string | string[]) {
    if (typeof input === 'string') {
        console.log(input);
    } else {
        input.forEach(item => console.log(item));
    }
}

display("Single");
display(["Multi", "Item", "List"]);

Output:

Single
Multi
Item
List

Union Type Arrrays

let mixedArray: number[] | string[];

mixedArray = [10, 20, 30];
console.log("Numeric Array:");
mixedArray.forEach(num => console.log(num));

mixedArray = ["Apple", "Banana", "Cherry"];
console.log("String Array:");
mixedArray.forEach(str => console.log(str));

Output:

Numeric Array:
10
20
30
String Array:
Apple
Banana
Cherry

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.