Open In App

TypeScript Working with Union Types

Last Updated : 17 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to learn about Working with Union Types in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. In Typescript, the compiler will only allow an operation if it is valid for every member of the union.

For example, if you have the union string | number, you can’t use methods that are only available on a string or only available on a number. To handle this problem, we need to use type guards/ type assertions to narrow down the type within the union before performing the operation.

Problems Arise While using the Union Type

Suppose, a function takes a parameter which is a union type, and wants to perform an operation that is specific to one of the types in the union. TypeScript may not allow this operation because it needs to ensure that the operation is valid for all possible types within the union.

Example: In this example, TypeScript raises an error because the length property is specific to strings, and it cannot guarantee that input is always a string when working with the union type string | number.

Javascript
function printLength(input: string | number) {
    console.log(input.length); 

    // Error: Property 'length' does not exist 
    // on type 'string | number'.
}

Output:z89

Solution of the Above Problem

To address this issue, we can use type assertions or type guards to narrow down the type within the union before performing the operation.

Example: We ae using typeof to do the narrowing for above example code.

Javascript
function printLength(input: string | number) {
    if (typeof input === 'string') {
        
        // OK, input is asserted as string type
        console.log(input.length); 
    } else {
        console.log('Not a string');
    }
}

printLength("GeeksforGeeks")

Output:

z90

Example 2: Sometimes you’ll have a union where all the members have something in common. For example, both arrays and strings have a slice method. If every member in a union has a property in common, you can use that property without narrowing:

Javascript
// Return type is inferred as number[] | string
function getFirstFour(x: number[] | string) {
    return x.slice(0, 4);
}

console.log(getFirstFour("GeeksforGeeks"))

Output:z91

Example 3: You can use union types to handle different types of data in a function parameter or return value. Here’s an example where a function can accept either a string or an array of strings and return the length or total length respectively:

JavaScript
function lengthOrTotalLength(data: string | string[]): number {
    if (typeof data === 'string') {
        return data.length;
    } else {
        return data.reduce((acc, str) => acc + str.length, 0);
    }
}

console.log(lengthOrTotalLength("Hello")); // Output: 5
console.log(lengthOrTotalLength(["Hello", "World"])); // Output: 10 (5 + 5)

Output:

5
10


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads