TypeScript Union
Back to: TypeScript Tutorial
TypeScript is a superset of JavaScript that adds types to JavaScript. With TypeScript, we can define the type of variables, functions, and parameters. In TypeScript, a union type is a type formed by combining two or more other types. In this lesson, we will discuss TypeScript union in detail with a code example.
What is TypeScript Union?
A union type in TypeScript is a type that can represent values of multiple types. It is formed by using the vertical bar |
to separate the types. For example, the union type string | number
represents a type that can hold either a string or a number.
Union types are useful when a function or a variable can accept different types of input. They allow us to define more flexible types that can handle different types of data.
Syntax of TypeScript Union
The syntax for defining a union type in TypeScript is:
type UnionType = Type1 | Type2 | Type3 | ... | TypeN;
where Type1
, Type2
, Type3
, …, TypeN
are the types that are being combined.
TypeScript Union Example
Let’s look at an example of using a union type in TypeScript. Suppose we want to create a function that can accept either a string or a number as its parameter.
function printData(data: string | number): void { console.log(data); } printData("Hello, TypeScript!"); // Output: Hello, TypeScript! printData(123); // Output: 123
In the above code, we defined a function printData
that takes a parameter data
of type string | number
. The function simply logs the value of data
to the console.
We then called the printData
function with a string argument and a number argument. In both cases, the function was able to handle the input correctly because of the union type.
Conclusion
In conclusion, TypeScript union is a powerful feature that allows us to define more flexible types in TypeScript. By combining multiple types using the vertical bar |
, we can create a union type that can hold values of different types. Union types are useful when we need to define a variable, function, or parameter that can accept different types of input.