Union types
- TypeScript course
- Beginner
- Lesson 59/89
- 4 min
Learn union, specifying one of several types.
What is a union type?
A union type states that a value can be one of several types. The types are separated by the | (pipe) sign. For example string | number says the value can be either a string or a number.
let id: string | number;
id = "TS-101";
id = 42;This is practical when an identifier can appear in both a text and a number form.
Type narrowing
When using a union type, TypeScript needs to know which type it currently is. You narrow the type with typeof to perform the right operations. In each branch only the methods of that branch's type are available.
function printId(id: string | number) {
if (typeof id === "string") {
console.log(id.toUpperCase());
} else {
console.log(id * 2);
}
}
printId("abc");
printId(5);Practice Write a format function with a union
Write a function format(input: string | number): string. Narrow with typeof: if it is a string, return toUpperCase(); if it is a number, return "N-" + input. Print the result of both calls.
Starter code
// format fonksiyonunu yaz
// parametre input: string veya number
// string ise büyük harfe çevir ve döndür
// number ise başına N- ön ekini ekle ve döndürSample solution
function format(input: string | number): string {
if (typeof input === "string") {
return input.toUpperCase();
} else {
return "N-" + input;
}
}
console.log(format("hello"));
console.log(format(42));Expected output
HELLO N-42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does it mean for a variable to have the type string | number?
let id: string | number = 42;- The value cannot be any type
- The value can be either string or number Correct answer
- The value must be both string and number
- The value can only be number
Explanation: A union lets you pick one of the types; the value can be any of the listed types.
2 Complete the union operator
let id: string ____ = 42;
let id: string | number = 42;
Explanation: A union combines types with the | operator. string | number means the value can be either string or number.
3 Union parts
| Term | Meaning |
|---|---|
| |
Combines types (or) |
typeof id === "string" |
Performs narrowing |
string | number |
An example union type |
null | undefined |
Combines two absent values |