带吸气剂的typescript可选属性

tru*_*ru7 4 getter object-literal optional typescript

这是一个简化的示例:

class PersonParms{
    name:string;
    lastName:string;
    age?:number;
    get fullName(){return this.name + " "+this.lastName;}
}

class Person{
    constructor(prms:PersonParms){
    }
}

new Person({name:'John',lastName:'Doe'})  // ts error: Property 'fullName' is missing in type '{ name: string; lastName: string; }'.
Run Code Online (Sandbox Code Playgroud)

这个想法是将一个文字对象作为PersonParms的inizizalizer传递,但是拥有该getter既不能声明该getter可选,也不能将该属性添加到对象文字中。还有另一种方法可以实现吗?

San*_*ero 6

截至 2020 年 4 月,还没有办法实现这一点。

对此有一个不确定的 PR: https ://github.com/microsoft/TypeScript/pull/16344

这里提出了通过接口提出的解决方案: https://github.com/microsoft/TypeScript/pull/16344

就我个人而言,该解决方案并不能满足我的需求,我宁愿将该财产声明为私有。

希望我们未来能有更好的运气。


Pav*_*vel 5

很有意思。我认为,您应该向TypeScript 报告问题,因为方法可以是可选的(请参见下文),而属性获取器则不是。这很奇怪。作为一种解决方法,我可以建议两个变体。一个不错的:

class PersonParms {
    name:string;
    lastName:string;
    age?: number;

    getFullName?() {return this.name + " "+this.lastName;}
}
Run Code Online (Sandbox Code Playgroud)

第二个是hacky,因为在传递给构造函数时,我们将所有属性设为可选。

class PersonParms {
    name:string;
    lastName:string;
    age?: number;

    get fullName(){return this.name + " "+this.lastName;}
}

class Person{
    constructor(prms: Partial<PersonParms>){
    }
}
Run Code Online (Sandbox Code Playgroud)


Bog*_*dan 2

我发现这个解决方案对我来说没问题:

class Person {
  name?:string;
  lastName?:string;
  age?: number;
  fullName?:string;

  constructor(public config: { name: string, lastName: string }) {
    Object.defineProperty(this,'fullName',{
           get(){return this.name + " " + this.lastName;}
          });

}
Run Code Online (Sandbox Code Playgroud)