Typescript default properties when casting

Is there a way to cast an object to a class type so that property values ​​are respected by default?

For instance:

class Person {
    name: string = "bob";
    age: number;
    sex: string;
}

var data = {
    "age": 23,
    "sex": "male"
}

var p = <Person>data;

console.log(p.name); // -> undefined

What is the easiest way to do this so that there is p.namea bob?

* Edit

It works:

var record : Person = Object.assign(new Person(), p);

Is this a good or bad practice?

+4
source share
2 answers

The easiest way an instance of a class gives you is to use the constructor initializer and make fields with default values ​​optional:

class Person {
  name?: string = "bob";
  age: number;
  sex: string;
  constructor(opt: Person) {
    Object.assign(this, opt);
  }
} 

or to be explicit in what is and is not optional for initialization.

class Person {
  name: string = "bob";
  age: number;
  sex: string;
  constructor(opt: { name?: string, age: number; sex: string; }) {
    Object.assign(this, opt);
  }
}

or, if you don’t care what is given, just make the initializer fields all optional:

class Person {
  name: string = "bob";
  age: number;
  sex: string;
  constructor(opt?: Partial<Person>) {
    Object.assign(this, opt);
  }
}

, , , :

var data = {
    "age": 23,
    "sex": "male"
}

var p1:Person = {name:"bob", ... data}; // or
var p2:Person = {new Person(), ... data};
+3

( casting); , .

.

+1

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


All Articles