Created
August 27, 2017 09:51
-
-
Save mishrsud/59d8d6b253872a81109d6f9d99edfec2 to your computer and use it in GitHub Desktop.
TypeScript: Use generics to access property if object is not null
This file contains hidden or 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
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