Summary - Union & intersection
- TypeScript course
- Beginner
- Lesson 62/89
- 4 min
Write a payment model by combining union and intersection.
Union and intersection together
You can build complex models by combining union and intersection. Parentheses set precedence: the union is applied first, then the intersection.
interface Identifiable { id: string; }
interface CashPay { method: "cash"; amount: number; }
interface CardPay { method: "card"; cardNumber: string; }
type Payment = (CashPay | CardPay) & Identifiable;
const p: Payment = { id: "p1", method: "cash", amount: 100 };Every payment has an identifier and can be either cash or card.
Practice Build a payment model
Define an Identifiable interface with id: string. Define a CashPay interface with method: "cash" and amount: number. Define a CardPay interface with method: "card" and cardNumber: string. Define the Payment type as (CashPay | CardPay) & Identifiable. The function handlePayment(p: Payment): string should return p.id + ":" + p.method and print the result.
Starter code
// Identifiable arayüzünü tanımla: id: string
// CashPay arayüzünü tanımla: method cash, amount: number
// CardPay arayüzünü tanımla: method card, cardNumber: string
// Payment = (CashPay | CardPay) & Identifiable
// handlePayment(p: Payment): string döndürür, id ve method arasına iki nokta koySample solution
interface Identifiable { id: string; }
interface CashPay { method: "cash"; amount: number; }
interface CardPay { method: "card"; cardNumber: string; }
type Payment = (CashPay | CardPay) & Identifiable;
function handlePayment(p: Payment): string {
return p.id + ":" + p.method;
}
const payment: Payment = { id: "p1", method: "cash", amount: 100 };
console.log(handlePayment(payment));Expected output
p1:cash
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which of the following type X definitions uses both union and intersection?
- type X = A;
- type X = A | B;
- type X = (A | B) & C; Correct answer
- type X = A & B;
Explanation: Inside the parentheses, A | B is a union; outside, & C is an intersection. This definition uses both concepts together.
2 Complete the payment model
type Payment = (Cash | Card) ____ Identifiable;
type Payment = (Cash | Card) & Identifiable;
Explanation: To intersect the union in parentheses with Identifiable, you need &. (Cash | Card) & Identifiable says every payment has an id and is either cash or card.
3 Combined model parts
| Term | Meaning |
|---|---|
| |
Or type operator |
& |
And type operator |
(A | B) & C |
Union first, then intersection |
"cash" | "card" |
A union of two string literals |