Created
September 22, 2020 00:03
-
-
Save neopryn/671686f915ec4e13d68c20809c3f5b85 to your computer and use it in GitHub Desktop.
TS Discriminant Union
This file contains 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
type Square = { type: "square", edgeLength: number } | |
type Circle = { type: "circle", radius: number } | |
// Here's our Discriminant Union | |
type Shape = Square | Circle | |
function exhaustiveCheck(x: never): never { | |
throw new Error("Didn't expect to get here"); | |
} | |
const imASquare: Square = { type: "square", edgeLength: 20 } | |
const getShapeArea = (x: Shape) => { | |
switch(x.type) { | |
case "square": | |
// The compiler will uniquely identify that x is a Square | |
// because it could infer it from the type property, amazing! | |
return x.edgeLength * x.edgeLength | |
case "circle": | |
return x.radius * x.radius * Math.PI | |
default: | |
// At this point, if you've exhausted all possible values of | |
// `type`, then x in this branch is `never`. If not then the compiler | |
// will throw an error for matching a value with `never`. | |
return exhaustiveCheck(x) | |
} | |
} | |
getShapeArea(imASquare) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment