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};
var p2:Person = {new Person(), ... data};