Skip to content

Instantly share code, notes, and snippets.

@AhsanAyaz
Created September 6, 2019 07:17
Show Gist options
  • Save AhsanAyaz/77d0e1b1e40a882f4c974acda788ff08 to your computer and use it in GitHub Desktop.
Save AhsanAyaz/77d0e1b1e40a882f4c974acda788ff08 to your computer and use it in GitHub Desktop.
Understanding Discriminated Unions in Typescript
function evaluatePrice(vehicle: Vehicle) {
switch(vehicle.vType) {
case "car":
return vehicle.transmission * evaluationFactor;
case "truck":
return vehicle.capacity * evaluationFactor;
case "motorcycle":
return vehicle.make * evaluationFactor;
default:
const invalidVehicle: never = vehicle;
return throw new Error(`Unknown vehicle: ${invalidVehicle}`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment