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

Kar*_*ner 7 javascript typescript angular

我的问题:

我需要区分typescript类的private,public和getter(get X())属性.

我的项目:

我有一个Angular项目,它有一个模型设计模式.阿卡.用户模型看起来像这样

class UserModel extends BaseModel {
    private _id: number;

    get id() { return this._id; }
    set id( _id: number ) { this._id = _id; }
}
Run Code Online (Sandbox Code Playgroud)

要将这些模型发送到后端,我只是JSON.stringify()它们,如果用户id设置为13,则返回一个这样的对象

{
    _id: 13
}
Run Code Online (Sandbox Code Playgroud)

现在我需要修改UserModel上的toJSON()函数,这样我将返回get X()变量,而不是返回对象的私有属性.输出应该如下所示.

{
    id: 13
}
Run Code Online (Sandbox Code Playgroud)

我创建了这个简单的函数,以检索对象的所有属性,但这给了我私有属性和get属性.

abstract class BaseModel {
    public propsToObj() : {[key: string]: any} {
        let ret: any = {};

        for (var prop in this) {
            ret[prop] = this[prop];
        }

        return ret;
    }
}
Run Code Online (Sandbox Code Playgroud)

并且toJSON函数看起来像这样

class UserModel extends BaseModel {
    private _id: number;

    get id() { return this._id; }
    set id( _id: number ) { this._id = _id; }

    toJSON() {
        return this.propsToObj();
    }
}
Run Code Online (Sandbox Code Playgroud)

字符串化UserModel的结果如下所示

{
    _id: 13,
    id: 13
}
Run Code Online (Sandbox Code Playgroud)

总之,我需要知道类的属性的可见性和类型(getter或常规变量?),我将如何实现这一目标?

Art*_*yan 4

你的propsToObj()工作错误,它只获取所有属性,你需要更改它,以便它只获取吸气剂,例如你可以使用这个

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Object.getOwnPropertyDescriptor将获取属性的描述符,从中您可以检查描述符中是否有 get 函数,如果是,则您的属性是 getter,如果没有,则为常规属性,您可以在此处阅读有关描述符的更多信息MDN(descriptors)

你问的最后一个问题

我需要知道类上属性的可见性和类型,我将如何实现这一点?

据我所知,您无法获得属性的可见性,至于类型,如果您想知道可以使用的属性的数据类型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;
    }
Run Code Online (Sandbox Code Playgroud)