Skip to content

Instantly share code, notes, and snippets.

@mishrsud
Created August 27, 2017 09:51
Show Gist options
  • Save mishrsud/59d8d6b253872a81109d6f9d99edfec2 to your computer and use it in GitHub Desktop.
Save mishrsud/59d8d6b253872a81109d6f9d99edfec2 to your computer and use it in GitHub Desktop.
TypeScript: Use generics to access property if object is not null
class Person {
firstname: string;
lastname: string;
constructor(firstname: string, lastname: string) {
this.firstname = firstname;
this.lastname = lastname;
}
}
let p = new Person('Sudhanshu', 'Mishra');
let q: Person;
function accessPropIfNotNull<T>(arg: T, prop: string): T {
if (arg != null && arg.hasOwnProperty(prop)) {
return arg[prop];
}
return null;
}
console.log(accessPropIfNotNull(p, 'firstname')); // returns firstname
console.log(accessPropIfNotNull(q, 'firstname')); // returns null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment