It appears that there may be some confusion between TypeScript typings and JavaScript runtime code in your project. Understanding the distinction between the two can greatly benefit you when working on your development projects. TypeScript is primarily a tool to assist during development, providing helpful typings and syntax which are not actually seen by the machine running the code. Once the TypeScript code is compiled down to JavaScript, it closely resembles the original code with all TypeScript-specific elements removed.
Below is an example of how your code looks after compilation:
// my-file.js
export function InitializeDefaultModelObject() {
const root = {};
Object.keys(root).forEach(key => {
if (typeof root[key] === 'object')
root[key] = {};
});
return root;
}
// file-that-imported-my-file.js
this.ProjectModel = InitializeDefaultModelObject();
console.table(this.ProjectModel);
If you have experience with regular JavaScript, you might find that the absence of generics or typings could be causing issues. The current function does not take any parameters and will always output an empty object as a result.
To create a more scalable solution that works for objects of any type in all scenarios, additional considerations need to be made. Here is a modified version of your original code that attempts to address this issue:
export function InitializeDefaultModelObject(originalObj) {
var sortaCopiedObj = {};
Object.keys(originalObj).forEach(key => {
var typeOfField = typeof originalObj[key];
if (typeOfField === 'object') sortaCopiedObj[key] = {};
});
return sortaCopiedObj;
}
For this approach to work effectively, it requires passing in literal objects without prototypes, disregarding non-object field values, and ignoring nested fields of copied object properties. If these limitations are acceptable for your use case, then this solution may suffice. However, dealing with prototypes and nested objects may require a different approach, such as converting the object into a class:
class MyClass {
a = { innerProperty: {} };
b = "hey!";
}
// Each instance has the same properties but is unique
var x = new MyClass();
var y = new MyClass();
var z = new MyClass();