【问题标题】:Is there a mechanism for converting a class instance to an object which contains keys of the public properties of the interface?是否有将类实例转换为包含接口公共属性键的对象的机制?
【发布时间】:2021-10-11 13:40:01
【问题描述】:

即如果我有一个看起来像的对象 Person

class PersonClass implements Person {
  private _name : string;
  private _age : number;
  get name() : string {return this._name}
  get age() : number (return this._age)
  constructor(name : string, age : number) {
     this._name = name;
     this._age = age;
  }
 }

我有公共属性的接口:

interface Person {
    name : string;
    age : string;
}

我需要做的是得到一个人的对象表示,它反映了 Person 接口,看起来像

{ name: John, age: 23}

有没有办法做到这一点?我尝试了强制转换(person as Person} 和 JSON.stringify 和对象分配,我似乎最终得到了包含私有数据 _name_age 但不包含接口成员 name 和“年龄”的对象

【问题讨论】:

标签: typescript


【解决方案1】:

似乎我想做的事情并不简单,所以我最终使用了一种方法,将所有状态变量保存在实现接口的私有对象中,以及何时我想要访问数据,我调用一个返回克隆或原始数据对象的函数。

类似:

interface Person {
    name : string;
    age : string;
}

class PersonClass implements Person {
   data : <Person>{} = {}
   constructor(name : string, age : number) {
       this.data.name = name;
       this.data.age = age;
   }
   get name() : string {return data.name}
   get age() : number {return data.age}
   get dataObject : return this.data;
}

当然不完美,因为私有数据可以通过.dataObject从类外部操作,但是如果dataObject返回数据的深拷贝,那么封装可以保持。一些额外的工作,但它使得从类中读取数据和写入后端更容易一些。

【讨论】:

    猜你喜欢
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多