typescript optional property with a getter

tru7 picture tru7 · Feb 10, 2018 · Viewed 7.1k times · Source

This is a simplified example:

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; }'.

The idea is to pass a literal object as the intizalizer of PersonParms but having that getter you can neither declare the getter optional or add the property to the object literal. Is there another way to achieve it?

Answer

Pavel picture Pavel · Feb 11, 2018

Very interesting. I think, you should report an issue to TypeScript, because methods can be optional (see below), but property getters not. It is strange.. As a workaround I can suggest two variants. A nice one:

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

    getFullName?() {return this.name + " "+this.lastName;}
}

And a second one, that is hacky, because there we make all the properties optional when passing to constructor.

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

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

class Person{
    constructor(prms: Partial<PersonParms>){
    }
}