class Data {
ID: number;
Activity?: string;
public getDataType(name: string) {
return typeof this[name];
}
constructor() { }
}
let _data = new Data()
_data.ID = 5
console.log(_data.getDataType("ID")) // Returns number
console.log(_data.getDataType("Activity")) //Returns undefined. But I want it to be string
I am looking to retrieve the types of all properties in my class, regardless of whether they have a value or not. However, when optional properties are not set, the getDataType function always returns undefined.
I could use an Interface instead of a Class, it doesn't matter. How can I solve this issue?
Thank you in advance!
Edit: My main objective is as follows.
I will receive data from a backend service with a model structure like the Data interface or class. Some properties of Data will be either numbers or strings and may be optional (potentially null or undefined). I want to display these fields to the user for editing on an HTML form, and then send the edited data back to the backend service for saving. When saving, I want to maintain the original data type. For example, if a field is a number, it should remain a number after the user's update and be sent to the backend endpoint as a number. I was using in HTML for each field. Because I want to dynamically generate HTML for each property using ngFor iteration. However, in order to preserve the value type (e.g. ensuring a number stays a number), I need to know the type of each property to display instead of . Therefore, my main goal is to dynamically preserve the data type according to my interface or class. I do not want to manually cast each field. If there is a different solution to achieve this, I would be happy to hear it.
Thank you once again!