Open In App

How to Return a Union Type in TypeScript ?

Last Updated : 08 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads