Skip to content

Instantly share code, notes, and snippets.

@blemoine
Last active March 31, 2018 20:39
Show Gist options
  • Save blemoine/ec2fc3c5584011d516c95b13f53a14e9 to your computer and use it in GitHub Desktop.
Save blemoine/ec2fc3c5584011d516c95b13f53a14e9 to your computer and use it in GitHub Desktop.
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