Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript optional property with a getter

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?

like image 519
tru7 Avatar asked Feb 10 '18 21:02

tru7


1 Answers

As of April 2020, there is NO way to implement this.

There is an inconclusive PR for this: https://github.com/microsoft/TypeScript/pull/16344

A proposed solution via an interface is presented here: https://github.com/microsoft/TypeScript/pull/16344

Personally, the solution did not meet my needs, and I rather declared the property as private.

Hopefully, we can have better luck in the future.

like image 76
Santiago M. Quintero Avatar answered Oct 19 '22 01:10

Santiago M. Quintero