Skip to content

Instantly share code, notes, and snippets.

@ulisesantana
Created October 19, 2021 16:26
Show Gist options
  • Save ulisesantana/46aef312b25f102ddf311b92032da116 to your computer and use it in GitHub Desktop.
Save ulisesantana/46aef312b25f102ddf311b92032da116 to your computer and use it in GitHub Desktop.
Ejemplo de tipos algebraicos en TypeScript
enum DiscountKind {
NoDiscount,
Special,
Resident,
Family,
Business
}
interface Discount {
kind: DiscountKind;
percentage: number;
}
type NoDiscount = Discount & { kind: DiscountKind.NoDiscount }
type SpecialResident = Discount & { kind: DiscountKind.Special }
type Resident = Discount & { kind: DiscountKind.Resident }
type Family = Discount & { kind: DiscountKind.Family }
type Business = Discount & { kind: DiscountKind.Business }
type SubsidyPlusBusiness = { business: Business, resident: Resident }
type SpanishSubsidy =
| SpecialResident
| Resident
| Family
type FlightDiscount =
| SpanishSubsidy
| Business
| SubsidyPlusBusiness
| NoDiscount
function handleFlightDiscount(discount: FlightDiscount): number {
if ('business' in discount) {
return discount.business.percentage + discount.resident.percentage
}
switch (discount.kind) {
case DiscountKind.NoDiscount: {
return discount.percentage
}
case DiscountKind.Special: {
return discount.percentage
}
case DiscountKind.Resident: {
return discount.percentage
}
case DiscountKind.Family: {
return discount.percentage
}
case DiscountKind.Business: {
return discount.percentage
}
}
}
console.log(handleFlightDiscount({ kind: DiscountKind.NoDiscount, percentage: 12 }))
console.log(handleFlightDiscount({ kind: DiscountKind.Special, percentage: 12 }))
console.log(handleFlightDiscount({ kind: DiscountKind.Resident, percentage: 12 }))
console.log(handleFlightDiscount({ kind: DiscountKind.Family, percentage: 12 }))
console.log(handleFlightDiscount({ kind: DiscountKind.Business, percentage: 12 }))
console.log(handleFlightDiscount({ business: { kind: DiscountKind.Business, percentage: 12 }, resident: { kind: DiscountKind.Resident, percentage: 34} }))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment