Open In App

TypeScript Defining a Union Type

Last Updated : 25 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to learn about Defining a Union Type in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. In TypeScript, a union type allows a variable to have one of several possible types. You can define a union type by using the | (OR) operator to specify multiple types as options.

Syntax:

type UnionType = Type1 | Type2 | Type3 | ...;

Where-

  • UnionType is the name you choose for your custom union type.
  • Type1, Type2, Type3, …: these are the individual types that you want to include in the union. You can specify any number of types, and the variable of UnionType can have values of any of these types. This can be string, number, etc

Example 1: In this example, We define a union type called Result that can hold values of either number or string types. We declare a variable value of type Result and assign it different values, including a number and a string.TypeScript will allow assignments of values that are either numbers or strings, but it will raise an error when you try to assign a boolean value, as it’s not part of the union type.

 

Javascript




// Step 1: Identify the Types
type Result = number | string;
  
// Step 2: Define the Union Type
  
// Step 3: Use the Union Type
let value: Result;
// Valid, as 42 is a number
value = 42;
// Valid, as "Hello" is a string
value = "Hello! GeeksforGeeks";
// value = true;
// Error, as boolean is not part of the union type
// Output depends on the assigned value
console.log(value);
  
// Step 4: Compile and Verify


Output:z63

Example 2: This example shows ‘narrowing’ in union type. we have used typeof checks as type guards to narrow down the possible types within the union. Depending on the type, we perform different operations and log messages. We call the narrowUnion function with values of different types, such as a string, a number, a boolean, and null.

Javascript




// Define a union type
type MyUnion = string | number | boolean;
  
// Function to narrow the union type
function narrowUnion(value: MyUnion): void {
    if (typeof value === "string") {
        console.log("Value is a string:", value.toUpperCase());
    } else if (typeof value === "number") {
        console.log("Value is a number:", value * 2);
    } else if (typeof value === "boolean") {
        console.log("Value is a boolean:", !value);
    } else {
        console.log("Value is of an unknown type:", value);
    }
}
  
// Example usages
narrowUnion("GeeksforGeeks");
narrowUnion(99);
narrowUnion(true);
// It will show error
// Argument of type 'null' is not 
// assignable to parameter of type 'MyUnion'.
narrowUnion(null);


Output:z89



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads