Created
September 6, 2019 07:17
-
-
Save AhsanAyaz/77d0e1b1e40a882f4c974acda788ff08 to your computer and use it in GitHub Desktop.
Understanding Discriminated Unions in Typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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