A union type allows a variable, property, or function parameter to
accept more than one type. Union types are created using the
pipe | operator.
A union type allows a value to have more than one possible type.
let id: number | string;
id = 101;
id = "ST101";
Here, id can contain either a number or a string.
The basic syntax is:
type1 | type2
Example:
let value: string | number;
The pipe symbol | means "or" in a union type.
One of the most common union types allows either a string or a number.
let value: string | number;
value = "Hello";
value = 100;
A union can contain a string and a boolean.
let result: string | boolean;
result = "Success";
result = true;
A value can also be either a number or a boolean.
let value: number | boolean;
value = 100;
value = false;
A union can contain more than two types.
let value:
string |
number |
boolean;
value = "Hello";
value = 100;
value = true;
Union types can be used when declaring variables.
let studentId: number | string;
studentId = 101;
console.log(studentId);
studentId = "ST101";
console.log(studentId);
Function parameters can accept multiple types.
function printId(
id: number | string
) {
console.log(id);
}
printId(101);
printId("ST101");
A function can return more than one possible type.
function getValue(
condition: boolean
): string | number {
if (condition) {
return "Success";
}
return 100;
}
console.log(
getValue(true)
);
console.log(
getValue(false)
);
Interface properties can use union types.
interface Student {
id: number | string;
name: string;
}
const student: Student = {
id: 101,
name: "Amit"
};
The id property can contain either a number
or a string.
A variable with a union type can receive different allowed types.
let id: number | string;
id = 101;
id = "ST101";
id = 202;
Each assignment must match one of the types in the union.
Values outside the union are not allowed.
let id: number | string;
id = 101;
id = "ST101";
// id = true; // Error
Boolean is not part of the declared union.
A variable can contain either a string array or a number array.
let data: string[] | number[];
data = [
"HTML",
"CSS"
];
data = [
10,
20,
30
];
There is an important difference between a union of arrays and an array containing union values.
let values: (string | number)[] = [
"Amit",
100,
"Rahul",
200
];
Here, individual array elements can be either strings or numbers.
Union types can restrict a variable to specific values.
let status:
"pending" |
"approved" |
"rejected";
status = "pending";
status = "approved";
Only the specified values are allowed.
Union types are useful for fixed categories such as user roles.
let role:
"admin" |
"student" |
"teacher";
role = "admin";
role = "teacher";
When a value has multiple possible types, use
typeof to determine its current type.
function showValue(
value: string | number
) {
if (typeof value === "string") {
console.log(
value.toUpperCase()
);
}
if (typeof value === "number") {
console.log(
value.toFixed(2)
);
}
}
showValue("hello");
showValue(100);
Type narrowing means reducing a union to a more specific type before performing type-specific operations.
function display(
value: string | number
) {
if (typeof value === "string") {
console.log(
"String:",
value
);
} else {
console.log(
"Number:",
value
);
}
}
A union can explicitly allow null.
let username:
string | null;
username = "Amit";
username = null;
This is useful when a value may not currently exist.
A union can also allow undefined.
let phone:
string | undefined;
phone = "9876543210";
phone = undefined;
let value:
string |
null |
undefined;
value = "Hello";
value = null;
value = undefined;
All three values are allowed because they are included in the union.
A union can contain different object structures.
interface Admin {
name: string;
role: "admin";
}
interface Student {
name: string;
role: "student";
}
let user:
Admin | Student;
user = {
name: "Amit",
role: "admin"
};
user = {
name: "Rahul",
role: "student"
};
A common property can be used to distinguish between different object types.
interface Admin {
role: "admin";
name: string;
}
interface Student {
role: "student";
name: string;
}
type User =
Admin | Student;
function showUser(
user: User
) {
if (user.role === "admin") {
console.log(
"Admin:",
user.name
);
} else {
console.log(
"Student:",
user.name
);
}
}
Union types can be used for React component properties.
interface ButtonProps {
title: string;
size: "small" | "medium" | "large";
}
function Button(
props: ButtonProps
) {
return (
<button>
{props.title}
</button>
);
}
The size property accepts only the specified values.
React Native components can use union types for properties such as button variants or display modes.
interface ButtonProps {
title: string;
variant:
"primary" |
"secondary" |
"danger";
}
const Button = (
props: ButtonProps
) => {
return (
<View>
<Text>
{props.title}
</Text>
</View>
);
};
API responses can sometimes have different possible states. A union can describe these states.
interface SuccessResponse {
status: "success";
data: string;
}
interface ErrorResponse {
status: "error";
message: string;
}
type ApiResponse =
SuccessResponse |
ErrorResponse;
A common mistake is trying to use an operation that is not available on every type in the union.
function printValue(
value: string | number
) {
// value.toUpperCase();
// Error because number
// does not have toUpperCase()
}
Narrow the type before using a type-specific method.
Union types are useful when a value can legitimately have different possible types or values.
interface Student {
type: "student";
id: number | string;
name: string;
course: string;
}
interface Teacher {
type: "teacher";
id: number | string;
name: string;
subject: string;
}
type User =
Student | Teacher;
function showUser(
user: User
) {
console.log(
"Name:",
user.name
);
console.log(
"ID:",
user.id
);
if (user.type === "student") {
console.log(
"Course:",
user.course
);
} else {
console.log(
"Subject:",
user.subject
);
}
}
showUser({
type: "student",
id: 101,
name: "Amit",
course: "TypeScript"
});
showUser({
type: "teacher",
id: "T101",
name: "Rahul",
subject: "JavaScript"
});
Union types allow a value to belong to one of several specified types.
let value:
string |
number;
value = "Hello";
value = 100;
Use the | operator to create unions and use
type narrowing when you need to perform operations specific
to one member of the union.
| operator to create a union.null and undefined.Question: Which symbol is used to create a union type in TypeScript?