Javascript/Typescript-获取对象属性可见性和类型



我的问题:

我需要区分typescript类的private、public和getter(getX())属性。

我的项目:

我有一个Angular项目,它有一个模型设计模式。又称作用户模型看起来像这个

class UserModel extends BaseModel {
private _id: number;
get id() { return this._id; }
set id( _id: number ) { this._id = _id; }
}

为了将这些模型发送到后端,我只需要JSON.stringify()they,如果用户id设置为13,它会返回一个类似的对象

{
_id: 13
}

现在我需要修改UserModel上的toJSON()函数,这样我将只返回getX()变量,而不是返回对象的私有属性。输出应该是这样的。

{
id: 13
}

我制作了这个简单的函数,用于检索对象的所有属性,但它同时提供了私有属性和get属性。

abstract class BaseModel {
public propsToObj() : {[key: string]: any} {
let ret: any = {};
for (var prop in this) {
ret[prop] = this[prop];
}
return ret;
}
}

toJSON函数看起来像这个

class UserModel extends BaseModel {
private _id: number;
get id() { return this._id; }
set id( _id: number ) { this._id = _id; }
toJSON() {
return this.propsToObj();
}
}

字符串化UserModel的结果看起来像这个

{
_id: 13,
id: 13
}

总之,我需要知道类上属性的可见性和类型(getter或正则变量?),我将如何实现这一点?

您的propsToObj()工作错误,它只获得所有属性,您需要更改它,使其只获得getter,例如,您可以使用此

abstract class BaseModel {
public propsToObj() : {[key: string]: any} {
let ret: any = {};
for (const prop in this) {
const descriptor = Object.getOwnPropertyDescriptor(this.constructor.prototype, prop);
if (descriptor && typeof descriptor.get === 'function') {
ret[prop] = this[prop];
}
}
return ret;
}
}

Object.getOwnPropertyDescriptor将获得一个属性的描述符,您可以从中检查描述符中是否有get函数,如果是,则您的属性是getter,如果不是,则它是正则属性,您可以在这里阅读更多关于描述符的信息MDN(描述符)

你问的最后一个问题

我需要知道类上属性的可见性和类型,以及如何我能做到这一点吗?

正如我所知,你无法获得属性的可见性,至于类型,如果你想知道属性的数据类型,你可以使用typeof

propsToObj()方法中的示例:

public propsToObj() : {[key: string]: any} {
let ret: any = {};
for (const prop in this) {
const descriptor = Object.getOwnPropertyDescriptor(this.constructor.prototype, prop);
if (descriptor && typeof descriptor.get === 'function') {
ret[prop] = this[prop];
console.log(typeof ret[prop]); // just exaple how you can know type you can save it with property too if you need it
}
}
return ret;
}

最新更新