This is a follow up question to this. Here the object can have optional parameters and the undefinedAllLeadNodes will like below
Input:
class Person {
name: string = 'name';
address: {street?: string, pincode?: string} = {};
}
const undefperson = undefinedAllLeadNodes(new Person);
console.log(undefperson);
Output:
Person: {
"name": undefined,
"address": undefined
}
As you can see as address has no properties, it should return as undefined.
How can I make sure Undefine(defined here) type handles this? Currently it accepts undefperson.address.street = '';
But I want to let it throw an error with "address may be undefined"
Update:
export function undefineAllLeafProperties<T extends object>(obj : T) {
const keys : Array<keyof T> = Object.keys(obj) as Array<keyof T>;
if(keys.length === 0)
return undefined!;//This makes sure address is set to undefined. Now how to identify this with typescript conditionals so that when accessing undefperson.address.street it should say address may be undefined.
keys.forEach(key => {
if (obj[key] && typeof obj[key] === "object" && !Array.isArray(obj[key])) {
obj[key] = undefineAllLeafProperties(<any>obj[key]) as T[keyof T];
} else if(obj[key] && Array.isArray(obj[key])) {
obj[key] = undefined!;
} else {
obj[key] = undefined!;
}
});
return obj;
}