TypeScript Defining a Union Type
Last Updated :
25 Oct, 2023
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
type Result = number | string;
let value: Result;
value = 42;
value = "Hello! GeeksforGeeks" ;
console.log(value);
|
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.
Javascript
type MyUnion = string | number | boolean;
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);
}
}
narrowUnion( "GeeksforGeeks" );
narrowUnion(99);
narrowUnion( true );
narrowUnion( null );
|
Output:
Share your thoughts in the comments
Please Login to comment...