Skip to content

Instantly share code, notes, and snippets.

@AhsanAyaz
Created September 6, 2019 07:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AhsanAyaz/438a0e4dcc8721c2cdaf1be078446023 to your computer and use it in GitHub Desktop.
Save AhsanAyaz/438a0e4dcc8721c2cdaf1be078446023 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;
case "bicycle":
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