-
-
Save blemoine/ec2fc3c5584011d516c95b13f53a14e9 to your computer and use it in GitHub Desktop.
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
function hasAttributeName(a: object): a is { name: string } { | |
return typeof ((a as any).name) === 'string'; | |
} | |
const user: object = {name: 'Georges'}; | |
console.log(user.name) // Compile error: Property 'name' does not exist on type 'object': | |
if (hasAttributeName(user)) { | |
console.log(user.name) // Compile fine. | |
// With the type guard, the compiler now knows that user is of type {name: string} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment