TypeScript Working with Union Types
Last Updated :
17 May, 2024
In this article, we are going to learn about Working with Union Types in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. In Typescript, the compiler will only allow an operation if it is valid for every member of the union.
For example, if you have the union string | number, you can’t use methods that are only available on a string or only available on a number. To handle this problem, we need to use type guards/ type assertions to narrow down the type within the union before performing the operation.
Problems Arise While using the Union Type
Suppose, a function takes a parameter which is a union type, and wants to perform an operation that is specific to one of the types in the union. TypeScript may not allow this operation because it needs to ensure that the operation is valid for all possible types within the union.
Example: In this example, TypeScript raises an error because the length property is specific to strings, and it cannot guarantee that input is always a string when working with the union type string | number.
JavaScript
function printLength(input: string | number) {
console.log(input.length);
// Error: Property 'length' does not exist
// on type 'string | number'.
}
Output:
Solution of the Above Problem
To address this issue, we can use type assertions or type guards to narrow down the type within the union before performing the operation.
Example: We ae using typeof to do the narrowing for above example code.
JavaScript
function printLength(input: string | number) {
if (typeof input === 'string') {
// OK, input is asserted as string type
console.log(input.length);
} else {
console.log('Not a string');
}
}
printLength("GeeksforGeeks")
Output:

Example 2: Sometimes you’ll have a union where all the members have something in common. For example, both arrays and strings have a slice method. If every member in a union has a property in common, you can use that property without narrowing:
JavaScript
// Return type is inferred as number[] | string
function getFirstFour(x: number[] | string) {
return x.slice(0, 4);
}
console.log(getFirstFour("GeeksforGeeks"))
Output:
Example 3: You can use union types to handle different types of data in a function parameter or return value. Here's an example where a function can accept either a string or an array of strings and return the length or total length respectively:
JavaScript
function lengthOrTotalLength(data: string | string[]): number {
if (typeof data === 'string') {
return data.length;
} else {
return data.reduce((acc, str) => acc + str.length, 0);
}
}
console.log(lengthOrTotalLength("Hello")); // Output: 5
console.log(lengthOrTotalLength(["Hello", "World"])); // Output: 10 (5 + 5)
Output:
5
10
Similar Reads
TypeScript Working with Generic Type Variables In TypeScript, working with generic type variables is a powerful feature that allows you to create functions and classes that can work with a variety of data types while maintaining type safety. Note: When you declare a generic function or class, you introduce a type variable enclosed in angle brack
2 min read
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
3 min read
TypeScript Union The TypeScript union has the ability to combine one or two different types of data (i.e., number, string, float, double, etc). It is the most powerful way to express a variable with multiple types. Use pipe ('|') symbol to combine two or more data types to achieve Union type. Syntax: (type1|type2|ty
3 min read
TypeScript Writing Good Overloads In this article, we are going to learn about Writing Good Overloads in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. For writing good overloads, you should always prefer parameters with union types instead of overloads when possible beca
3 min read
TypeScript Extract<Type, Union> Utility Type In this article, we are going to learn about Extract<Type, Union> utility type in TypeScript, TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tools at any scale. Extract<Type, Union> utility type is used to extract a subset of types from a
4 min read
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 va
4 min read
TypeScript Duck-Typing In TypeScript, the duck-typing feature ensures type safety. As a result of the duck-typing rule, the TypeScript compiler verifies that two objects are identical in terms of having matching properties and methods. This technique is used to compare two objects by determining if they have the same type
4 min read
Getting Started with TypeScript TypeScript is an open-source programming language developed by Microsoft that extends JavaScript by adding optional static typing to the language. It aims to make JavaScript development more scalable and maintainable, especially for large-scale projects. TypeScript code is transpiled into JavaScript
4 min read
TypeScript Structural Typing TypeScript type system is based on structural typing, therefore, TypeScriptâs type compatibility is determined by the structure (i.e., the properties and methods) rather than explicit declarations or names. In this article, we will learn in detail about TypeScript Structural Typing.What is Structura
5 min read
Data types in TypeScript In TypeScript, a data type defines the kind of values a variable can hold, ensuring type safety and enhancing code clarity.Primitive Types: Basic types like number, string, boolean, null, undefined, and symbol.Object Types: Complex structures including arrays, classes, interfaces, and functions.Prim
3 min read