Created
May 26, 2019 18:04
-
-
Save Luke-Rogerson/a07268495b105e1275cc88620b77f60c to your computer and use it in GitHub Desktop.
Use Javascript `in` operator for automatic type inference in TS
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
interface Admin { | |
id: string; | |
role: string; | |
} | |
interface User { | |
email: string; | |
} | |
function redirect(usr: Admin | User) { | |
// input can only be of type "Admin" or "User". If it passes that if condition, that means it has the "role" property on it. | |
// The only type that includes the "role" property is admin, so it must be admin | |
if ("role" in usr) { | |
routeToAdminPage(usr.role); | |
} | |
else { | |
routeToHomePage(usr.email); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment