Angular – Class initializers in TypeScript

One thing that is great in C# is the ability to initialise values on create like so: –

MyObject test = new MyObject { Name="Test", Description="This is a description" };

With the release of TypeScript 2.1 you can now do something similar: –

export class MyObject{
    public Name: string;
    public Description: string;

    public constructor(
        fields?: {
            Name?: string,
            Description?: string
        }) {
        if (fields) Object.assign(this, fields);
    }
}

Then you can use is like so:-

new MyObject({ Name:"Test", Description="This is a description" });

Just make sure that in your package.json that devDependencies has typescript 2.1 or higher.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s