There are two methods available:
public prop<K extends keyof ResponseInvitation.RootObject>(key: K) {
return this._has(key) ? this.user[key] : null;
}
private _has(prop: string): boolean {
return this.user.hasOwnProperty(prop);
}
To use these methods, you can do the following:
let prop = this.prop('profile'); // Returns an object
How to chain call this.prop
when the returned property is an object:
let prop = this.prop(this.prop('profile').organization);
In the scenario above, we first try to retrieve the property named profile
, which returns an object containing the property organization
as a string.
If I understand correctly, you require this additional logic:
private _has(prop: string): boolean {
let prop = this.user.hasOwnProperty(prop);
if (typeof prop == 'object') {
return this._has(prop);
}
}
I encountered a similar issue and managed to rewrite the logic with the following code:
interface RootObject {
name: string;
organization: Org;
}
interface Org {
name: string;
}
class A {
public user: any;
public last: string;
public prop<K extends keyof RootObject>(key: K) {
let prop = this._has(key) ? this.user[key] : null;
if (key == this.last) {
return prop;
}
if (typeof prop == 'object') {
let k = Object.keys(prop)[0] as K;
this.user = prop;
return this.prop(k);
}
}
private _has(prop: string): boolean {
return this.user.hasOwnProperty(prop);
}
public propString(properties: string) {
this.last = properties.split('.').slice(-1).pop();
}
}
let b = {
'organization': {
'name': 'Oleg'
}
};
let a = new A();
a.user = b;
a.propString('organization.name');
let d = a.prop('organization');
console.log(d);