基本上,我的问题归结为以下事实:我无法拥有与用于getter或setter的名称相同的属性。 此问题有更多详细信息:Duplicate declaration TypeScript Getter Setter。
因此,为了避免出现这种情况,我通过以下方式创建我的课程(此处仅显示其私有字段之一):
export class RFilter
{
private _phone_model: string;
constructor(task: Task)
{
this.phone_model = task.phone_model;
}
set phone_model(val: string)
{
this._phone_model = val;
}
get phone_model(): string
{
return this._phone_model;
}
此问题是服务器希望该字段的名称为phone_model
,而不是_phone_model
。我知道我可以给我的getter和setter方法命名,例如Phone_model
,然后将私有字段重命名为phone_model
,但是...这违反约定。
处理此问题的正确方法是什么?
答案 0 :(得分:0)
So I did some checking and the following should bypass the manual JSON (I had the idea, but the nice code I have found on SO)
Add this on the top of your class (original code: Get properties of class in typescript / @nitzantomer):
public static getGetters(): string[] {
return Reflect.ownKeys(this.prototype).filter(name => {
return typeof Reflect.getOwnPropertyDescriptor(this.prototype, name)["get"] === "function";
}) as string[];
after that you can use
let rFilter = new RFilter();
rFilter.phone_model = "flashy phone";
let obj = {};
for (getter of RFilter.getGetters()) {
console.log(getter " - "+rFilter[getter]);
obj[name] = settings[name];
}
console.log(JSON.stringify(obj));