Stop Manually Assigning TypeScript Constructor Parameters

TypeScript is great – but it is different to other languages. It is worth spending a little time learning the differences, especially when it comes to the differences between JavaScript and TypeScript and the differences between C# and TypeScript.

One difference that I really like is automatic assignment of constructor parameters to the relevant property. So here is an example of some TypeScript code that I am seeing quite a lot.

class Person {
    private firstName: string;
    private lastName: string;
    
    constructor(firstName: string, lastName: string) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

In this short example, I have four lines of code that TypeScript can happily live without. Here is how it should really look:

class Person {
    constructor(private firstName: string, private lastName: string) {
    }
}

The design time and compile time tooling and the resulting JavaScript output are all identical, but you wrote less code. You can take a look at this on the TypeScript Playground. Here is the JavaScript:

var Person = (function () {
    function Person(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    return Person;
})();