Horje
How to Return a Union Type in TypeScript ?

In TypeScript, a union type is a powerful way to express a variable that can be one of several types. Union types are used when a function or variable is expected to support multiple types of input. Union types are defined using the pipe (|) symbol between two or more types. This indicates that a variable or return value can be any one of these types. Following are the methods through which one can return union type in TypeScript.

Union type as a return type of function

In the simplest form, you can specify a union type as the return type of a function. This approach is used when a function returns values of two or more types.

Syntax:

function functionName(parameters): TypeA | TypeB {
  // function body
}

Example: A function that returns either a string or a number. This example demonstrates a function getID that accepts and returns a union type of string | number. Depending on the type of argument passed, it returns either a string or a number.

JavaScript
function getID(id: string | number): string | number {
    return id;
}

console.log(getID(101));
console.log(getID("202"));

Output:

101
202

Overloading Functions

Function overloading in TypeScript allows you to have multiple function signatures for the same function name, each with different return types. This is a more sophisticated way to handle union types as return values, especially when the return type is dependent on the function’s input types.

Syntax:

function functionName(parameters: TypeA): ReturnTypeA;
function functionName(parameters: TypeB): ReturnTypeB;
function functionName(parameters: any): any {
  // function body
}

Example: Overloading a function to return different types based on input. This example shows a function getValue that is overloaded to return a string when the input is a string and a number when the input is a number.

JavaScript
function getValue(key: string): string;
function getValue(key: number): number;
function getValue(key: any): any {
    if (typeof key === "string") {
        return `Value is a string: ${key}`;
    } else if (typeof key === "number") {
        return `Value is a number: ${key}`;
    }
}

console.log(getValue("username"));
console.log(getValue(123));

Output:

Value is a string: username
Value is a number: 123

Returning Objects with Union Types

Returning objects that may contain union types within their properties is used when you want to return complex data structures that might have properties of different types.

Syntax:

function functionName(parameters): { keyA: TypeA; keyB: TypeB | TypeC } {
  // function body
}

Example: Returning an object with properties as union types. In this example, the getUserStatus function returns an object with a status property that is a union type ‘active’ | ‘inactive’.

JavaScript
function getUserStatus(id: number): {
    name: string,
    status: "active" | "inactive",
} {
    if (id > 0) {
        return { name: "User1", status: "active" };
    } else {
        return { name: "User2", status: "inactive" };
    }
}

// { name: "User1", status: "active" }
console.log(getUserStatus(1));

// { name: "User2", status: "inactive" }
console.log(getUserStatus(-1));

Output:

{ name: 'User1', status: 'active' }
{ name: 'User2', status: 'inactive' }

Using Type Aliases for Union Types

Type aliases can be used to define a union type that can then be used as a return type for a function. This approach makes the code more readable and maintainable, especially for complex union types.

Syntax:

type MyUnionType = TypeA | TypeB;
function functionName(parameters): MyUnionType {
  // function body
}

Example: Using type aliases for a function’s return type. Here, a type alias ID is defined for the union type string | number and used as the return type of the getIdentifier function.

JavaScript
type ID = string | number;

function getIdentifier(id: ID): ID {
    return id;
}

console.log(getIdentifier(456)); // 456
console.log(getIdentifier("abc")); // "abc"

Output:

456
abc

Using Generic Functions with Union Types

You can define a generic function that accepts a type parameter and uses this parameter within a union type for the return value. The function can then decide which type to return based on the input or specific conditions within the function body.

Example Here’s an example of a generic function that returns a value from a union type based on a condition:

JavaScript
function getValue<T extends string | number>(value: T): T | { error: string } {
    if (typeof value === "string") {
        if (value.trim() === "") {
            return { error: "String is empty" };
        } else {
            return value; 
        }
    } else if (typeof value === "number") {
        if (value < 0) {
            return { error: "Number is negative" }; 
        } else {
            return value; 
        }
    }
    throw new Error("Unsupported type");
}


console.log(getValue("Hello World")); 
console.log(getValue(123));          
console.log(getValue(""));            
console.log(getValue(-10));          

Output:

"Hello World"
123
{ error: "String is empty" }
{ error: "Number is negative" }



Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
Slice() From Dplyr In R Slice() From Dplyr In R
How to Split String by Delimiter/Separator in PHP? How to Split String by Delimiter/Separator in PHP?
How to Merge Child Object Value to Parent Key Based on Key Name in JavaScript ? How to Merge Child Object Value to Parent Key Based on Key Name in JavaScript ?
How to Search Character in List of Array Object Inside an Array Object in JavaScript ? How to Search Character in List of Array Object Inside an Array Object in JavaScript ?
What are Recursive Types &amp; Interfaces in TypeScript ? What are Recursive Types &amp; Interfaces in TypeScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12