Sometimes, we want to add field initializers with TypeScript.
In this article, we’ll look at how to add field initializers with TypeScript.
How to add field initializers with TypeScript?
To add field initializers with TypeScript, we can use the Partial
type.
For instance, we write
class Person {
public name: string = "default";
public address: string = "default";
public age: number = 0;
public constructor(init?: Partial<Person>) {
Object.assign(this, init);
}
}
const p = new Person({ name: "John" });
to set the init
parameter of the Person
constructor to Partial<Person>
so that it takes an object with any property of the Person
class.
We add ?
after init
to make it optional.
Then we merge the properties of init
into this
with
Object.assign(this, init);
Next, we create a Person
instance with
const p = new Person({ name: "John" });
Conclusion
To add field initializers with TypeScript, we can use the Partial
type.