How can one loop through the properties of a class in TypeScript? Take the following class for example:
export class Task implements Itask {
public Id: number = 0;
public Name: string;
public Description: string;
public Completed: boolean = false;
public TaskType: TaskType;
}
Im want to retrieve the properties, hence: ["Id", Name", "Description", "Completed", "TaskType"]
Tried
GetTaskHeaders = () => {
const _self = this;
const tHead = $('<thead />').append('<tr />');
for (let i = 0; typeof TodoApp.Task.arguments; i++) {
const th = $('<th />');
th.append(TodoApp.Task.arguments[i]);
tHead.append(th);
}
console.log(tHead);
return tHead;
};
Unfortunately without success, i know using "TodoApp.Task.arguments" is incorrect. However, can someone show me the right way please?
See How do I loop through or enumerate a JavaScript object?
In your case, something like:
Let's consider that all "not defined" properties i.e. all properties that are defined in the typescript class like (I wrote "not defined" and not
undefined
for a reason that will be clear below)will not be enumerated by any of
Object.keys
orthis.hasOwnProperty(k)
since the autogen javascript has no knowledge of those properties. You have only one option, when you create your typescript class, that is to initialize all properties to default values likeAt this point you will get all the properties of
A
instance like in this mapping iteration from a dictionaryIf you don't like the default values solution, you can still do this using the magic
undefined
javascript keyword so that you do:At this point the javascript counterpart will have all properties in the model and you will iterate them with
Object.keys(this)
or inspect them via thethis.hasOwnProperty