Challenge 3: Unions
- TypeScript course
- Beginner
- Lesson 88/89
- 6 min
Design a model using union and intersection.
Challenge 3: Unions
In this challenge you will use the union (|) and intersection (&) operators to design color and money models. First you will define colors with a literal union, then a money type with intersection.
Practice Color and hex function
Define a Color type as "red" | "green" | "blue". Write a function hex(c: Color): string: return "#ff0000" for "red", "#00ff00" for "green", and "#0000ff" for "blue". Print the results of hex("red") and hex("blue").
Starter code
// Color türü: "red", "green", "blue"
// hex(c: Color): string yaz
// red -> "#ff0000", green -> "#00ff00", blue -> "#0000ff"
// iki çağrıyı yazdırSample solution
type Color = "red" | "green" | "blue";
function hex(c: Color): string {
if (c === "red") {
return "#ff0000";
} else if (c === "green") {
return "#00ff00";
} else {
return "#0000ff";
}
}
console.log(hex("red"));
console.log(hex("blue"));Expected output
#ff0000 #0000ff
Practice Combine Price and Currency
Define a Price interface: amount: number. Define a Currency interface: code: string. Define the Money type as Price & Currency. Create a Money object and print its code field.
Starter code
// Price arayüzü: amount: number
// Currency arayüzü: code: string
// Money = Price & Currency
// bir Money oluştur ve code yazdırSample solution
interface Price { amount: number; }
interface Currency { code: string; }
type Money = Price & Currency;
const m: Money = { amount: 100, code: "TRY" };
console.log(m.code);Expected output
TRY
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What type does Price & Currency produce?
- Price or Currency
- Price and Currency combined Correct answer
- Only Price
- Only Currency
Explanation: Intersection (&) combines all fields of both types. The result contains fields from both Price and Currency.
2 Complete the union operator
type Color = "red" ____ "green" | "blue";
type Color = "red" | "green" | "blue";
Explanation: Color is a union of three literals with the pipe. & is intersection (would be never), || and + are not type operators.
3 Union operator parts
| Term | Meaning |
|---|---|
| |
Union (or) |
& |
Intersection (and) |
"red" | "green" | "blue" |
Three color literals |
Price & Currency |
Price and currency |