Last active
June 6, 2020 17:58
-
-
Save guayom/56ab7f946438f8f30945f1bf68060b3c to your computer and use it in GitHub Desktop.
Typescript patterns
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
// Use the Javascript "in" operator for automatic type inference | |
// https://egghead.io/lessons/typescript-use-the-javascript-in-operator-for-automatic-type-inference-in-typescript | |
interface Admin { | |
id: string; | |
role: string; | |
} | |
interface User { | |
email: string; | |
} | |
function redirect(user: Admin | User) { | |
if ("role" in user) { | |
// The type is Admin, because it has a property "role" | |
console.log(user.role); | |
} else { | |
console.log(user.email); | |
} | |
} |
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
// https://github.com/eggheadio-projects/practical-advanced-typescript-features/tree/4-infer-type-switch-statement | |
interface Action { | |
type: string; | |
} | |
const AddPerson = { | |
type = "Add", | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment