Stop manually assigning TypeScript constructor parameters

Stop manually assigning TypeScript constructor parameters

BackerLeader posted Originally published at stevefenton.co.uk 1 min read

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#, Java, 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;

        // Constructor logic
    }
}

This might well be how you do it in other languages, but it isn’t how you handle TypeScript constructor parameters… unless you really like typing the same thing quite a lot.

In particular we have four lines of code in the first attempt that you just don’t need in a TypeScript program, because the compiler can generate them for us. This is the logically identical equivalent of the Person class, written in proper TypeScript:

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

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

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

This works for any access modifier you add to TypeScript constructor parameters, so you can use this trick for public, protected, and private members that are being passed in as arguments.

2 Comments

2 votes
1
2 votes
1

More Posts

TypeScript Complexity Has Finally Reached the Point of Total Absurdity

Karol Modelskiverified - Apr 23

Your Tech Stack Isn’t Your Ceiling. Your Story Is

Karol Modelskiverified - Apr 9

I’m a Senior Dev and I’ve Forgotten How to Think Without a Prompt

Karol Modelskiverified - Mar 19

Merancang Backend Bisnis ISP: API Pelanggan, Paket Internet, Invoice, dan Tiket Support

Masbadar - Mar 13

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10
chevron_left

Related Jobs

View all jobs →

Commenters (This Week)

2 comments
2 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!