Open In App

TypeScript Defining a Union Type

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-



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.

 






// 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:

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.




// 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:


Article Tags :