The simplest way that gives you an instance of the class is to use a constructor initialiser and make the fields with defaults optional:
class Person {
name?: string = "bob";
age: number;
sex: string;
constructor(opt: Person) {
Object.assign(this, opt);
}
}
or 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);
}
}
if you don't care about it being an instance of the class, but you want to enforce the fields and types then avoid casting and set the type of the variable explicitly instead:
var data = {
"age": 23,
"sex": "male"
}
var p1:Person = {name:"bob", ... data}; // or
var p2:Person = {new Person(), ... data};
var p:Person = {name="default", ... data}will work and enforce the type, but it isn't an instance of the class. For that you'd probably be better off with a class constructor that takes an initializer. see: stackoverflow.com/questions/14142071/…