Skip to content

Instantly share code, notes, and snippets.

@blemoine
Last active March 23, 2017 16:38
Show Gist options
  • Save blemoine/6e5ac99e792526be5636df524bfa6591 to your computer and use it in GitHub Desktop.
Save blemoine/6e5ac99e792526be5636df524bfa6591 to your computer and use it in GitHub Desktop.
function has<P extends string>(obj: object, prop: P): obj is {[K in P]: any} {
return obj && obj.hasOwnProperty(prop);
}
const testObj: object = null;
if (has(testObj, 'name')) {
//TypeScript know that testObj has the property name
console.log(testObj.name);
//console.log(testObj.firstname) wouldn't compile
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment