In TypeScript, a union type is a type that allows a value to be one of several specified types. It’s useful when you want to allow a variable to have multiple potential types. You define a union type using the vertical bar (|) to separate each type.
Example of Union Type
let data: string | number;
data = "Hello World"; // OK
data = 100; // OK
data = true; // Error: Type 'boolean' is not assignable to type 'string | number'.
In this example, the variable data can be either a string or a number, but not any other type like boolean.
Usage in Functions
function format(input: string | number): string {
if (typeof input === "string") {
return input.toUpperCase();
} else {
return input.toFixed(2);
}
}
console.log(format("Hello World")); // Output: "HELLO WORLD"
console.log(format(120)); // Output: "120.00"
Here, the format function accepts either a string or a number as its input and handles each type appropriately.
Union Types with Objects
type Cat = { name: string; purrs: boolean };
type Dog = { name: string; barks: boolean };
type Pet = Cat | Dog;
function makeSound(pet: Pet): string {
if ("purrs" in pet) {
return pet.name + " purrs.";
} else {
return pet.name + " barks.";
}
}
const cat: Cat = { name: "Pussy", purrs: true };
const dog: Dog = { name: "Tiger", barks: true };
console.log(makeSound(cat)); // Output: "Pussy purrs."
console.log(makeSound(dog)); // Output: "Tiger barks."
What is Union Type in TypeScript – Interview Questions
Q 1: What is union type?
Ans: It allows a variable to hold multiple types.
Q 2: Example of union type?
Ans: let value: string | number;
Q 3: Why use union types?
Ans: For flexibility with type safety.
Q 4: Can union types work with arrays?
Ans: Yes.
Q 5: Is runtime checking automatic?
Ans: No, it’s compile-time only.
What is Union Type in TypeScript – Objective Questions (MCQs)
Q1. A union type allows a variable to store:
Q2. Which symbol defines a union type?
Q3. Union type example:
Q4. Union types help in handling:
Q5. Union types improve: