Skip to content

Instantly share code, notes, and snippets.

@Luke-Rogerson
Created May 26, 2019 18:04
Show Gist options
  • Save Luke-Rogerson/a07268495b105e1275cc88620b77f60c to your computer and use it in GitHub Desktop.
Save Luke-Rogerson/a07268495b105e1275cc88620b77f60c to your computer and use it in GitHub Desktop.
Use Javascript `in` operator for automatic type inference in TS
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