Shorthand for a field initializer when a class has computed a property

Let's say I have a very simple class with a computed property:

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

Now I want to create an object of type Person :

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

This gives me an error:

Enter '{firstName: string; lastName: string; } 'is not assigned to the type' Person '. The 'fuillName' property is not in the type '{firstName: string; lastName: string; } ".

A? fullName is a read-only property. So I followed this question and implemented a partial initializer:

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

The same mistakes. I know I can do this:

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

But is there a shorthand for initializing a class using JSON syntax?

+5
source share
1 answer

If you define the Person class as follows:

  class Person { firstName?: string; lastName?: string; constructor(values: Object = {}) { Object.assign(this, values); } get fullName(): string { return this.firstName + ' ' + this.lastName; } } 

you can initialize a new user as follows:

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

Further:

  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"; 

Plunger Demo

+3
source

Source: https://habr.com/ru/post/1271477/


All Articles