加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 当类具有计算属性时字段初始值设定项的简写

发布时间:2020-12-17 10:25:12 所属栏目:安全 来源:网络整理
导读:假设我有一个非常简单的类,带有计算属性: class Person { firstName: string; lastName: string; get fuillName(): string { return this.firstName + ' ' + this.lastName; }} 现在我想创建一个Person类型的对象: let p: Person = { firstName: 'John',la
假设我有一个非常简单的类,带有计算属性:
class Person {
  firstName: string;
  lastName: string;

  get fuillName(): string {
    return this.firstName + ' ' + this.lastName;
  }
}

现在我想创建一个Person类型的对象:

let p: Person = {
  firstName: 'John',lastName: 'Smith'
};

这给了我一个错误:

Type ‘{ firstName: string; lastName: string; }’ is not assignable to type ‘Person’. Property ‘fuillName’ is missing in type ‘{ firstName: string; lastName: string; }’.

咦? fullName是只读属性.所以我按照this question执行了部分初始化程序:

constructor(init?: Partial<Person>) {
  Object.assign(this,init);
}

同样的错误.我知道我可以这样做:

let p = new Person();
p.firstName = 'John';
p.lastName = 'Smith';
console.debug(p.fullName);

但是有没有使用JSON语法初始化类的简写?

如果您定义Person类,如下所示:
class Person {
    firstName?: string;
    lastName?: string;

    constructor(values: Object = {}) {
      Object.assign(this,values);
    }

    get fullName(): string {
       return this.firstName + ' ' + this.lastName;
    }
  }

您可以按以下方式初始化新用户:

let p = new Person({firstName : 'John',lastName: 'Smith'}); //one line,two assignations
  console.log(p.fullName);

更进一步:

class Person {
     ....// as above
     set fullName(fullName: string){
         let splitName = fullName.split(" ");
         this.firstName = splitName[0] || '';
         this.lastName = splitName[1] || '';
     }
   }

   let p = new Person()
   p.fullName = "Paul Doe";

Plunker Demo

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读