union types typescript with code examples

Union Types in TypeScript

TypeScript is a statically typed programming language that builds on top of JavaScript. One of its features is the ability to declare union types, which allow a variable to have multiple types. This can be useful in situations where a value can have one of several possible types. In this article, we will explore what union types are and how to use them in TypeScript.

What are Union Types?

A union type is a type that represents a value that can be one of several types. In TypeScript, you can declare a union type using the pipe (|) symbol. For example, the following declaration says that a variable can be either a string or a number:

let myVariable: string | number;

You can then assign values of either type to this variable:

myVariable = "hello";
myVariable = 42;

It is important to note that once you have assigned a value to a union type variable, you can no longer change its type. This means that the following code will result in an error:

myVariable = "hello";
myVariable = 42;
myVariable = true; // Error: Type 'boolean' is not assignable to type 'string | number'.

How to use Union Types

There are several ways to use union types in TypeScript. One common use case is to create a type that represents a value that can be either a string or a number. For example, you could use a union type to represent the ID of an object, which could be either a string or a number:

type ObjectId = string | number;

You can then use this type when declaring variables that represent object IDs:

let objectId: ObjectId;
objectId = "abc123";
objectId = 42;

Another use case for union types is to create a type that represents a value that can be either an object or an array. For example, you could use a union type to represent a data structure that could either be a single object or an array of objects:

type DataStructure = object | object[];

You can then use this type when declaring variables that represent data structures:

let data: DataStructure;
data = { name: "John Doe" };
data = [{ name: "Jane Doe" }, { name: "Jim Doe" }];

Conclusion

Union types are a powerful feature in TypeScript that allow you to declare variables that can have multiple types. This can be useful in situations where a value can have one of several possible types, such as an object ID that could be either a string or a number, or a data structure that could be either an object or an array. By using union types, you can ensure that your code is more type-safe and less prone to errors.
Type Guards in TypeScript

When working with union types, you may need to perform different actions based on the type of a value. In these cases, you can use type guards to narrow down the type of a value. TypeScript provides two ways to create type guards: typeof and instanceof.

The typeof type guard allows you to check if a value is of a specific primitive type. For example, you can use typeof to check if a value is a string:

if (typeof myVariable === "string") {
  console.log(`The length of the string is ${myVariable.length}.`);
}

The instanceof type guard allows you to check if a value is an instance of a specific class. For example, you can use instanceof to check if a value is an instance of the Array class:

if (myVariable instanceof Array) {
  console.log(`The length of the array is ${myVariable.length}.`);
}

TypeScript will use the type guard to narrow down the type of the value, allowing you to access properties that are specific to that type. For example, in the code above, you can access the length property of the string or array, because TypeScript knows that the type of the value is either string or Array.

Type Aliases in TypeScript

TypeScript also provides a feature called type aliases, which allow you to define a new name for a type. Type aliases are similar to interfaces, but they are less flexible. Type aliases can be used to define union types, as well as other types such as tuples, intersections, and more.

For example, you can use a type alias to define a union type that represents either a string or a number:

type StringOrNumber = string | number;

You can then use the type alias in the same way as you would use a union type directly:

let myVariable: StringOrNumber;
myVariable = "hello";
myVariable = 42;

Type aliases can be especially useful when working with complex types, such as intersections or tuples. By giving these types a descriptive name, you can make your code more readable and easier to understand.

In conclusion, union types, type guards, and type aliases are features of TypeScript that can help you write more type-safe and maintainable code. By using these features, you can ensure that your code is more robust and less prone to errors.

Popular questions

  1. What is a union type in TypeScript?

A union type in TypeScript is a type that can be one of multiple types. For example, a union type of string | number represents a value that can be either a string or a number.

  1. How do you declare a union type in TypeScript?

You declare a union type in TypeScript by using the pipe (|) operator. For example, the following code declares a variable myVariable that can be either a string or a number:

let myVariable: string | number;
  1. Can you provide an example of using a union type in TypeScript?

Certainly! Here's an example of using a union type in TypeScript:

let myVariable: string | number;
myVariable = "hello";
console.log(`The value is a string with value "${myVariable}".`);

myVariable = 42;
console.log(`The value is a number with value ${myVariable}.`);

In this example, myVariable can be either a string or a number, so we can assign it a string value and then a number value, and both will be valid.

  1. What is a type guard in TypeScript?

A type guard in TypeScript is a way to check the type of a value and narrow down its type in a type-safe manner. TypeScript provides two ways to create type guards: typeof and instanceof.

  1. Can you provide an example of using a type guard in TypeScript?

Sure! Here's an example of using a typeof type guard in TypeScript:

let myVariable: string | number;
myVariable = "hello";

if (typeof myVariable === "string") {
  console.log(`The value is a string with value "${myVariable}".`);
} else {
  console.log(`The value is a number with value ${myVariable}.`);
}

In this example, we use the typeof operator to check the type of myVariable. If it's a string, we log a message indicating that it's a string. If it's not a string, it must be a number, so we log a message indicating that it's a number. The type guard allows us to access the properties of myVariable with confidence, because we know its type.

Tag

TypeScript

Posts created 2498

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top