Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to implicitly set properties in constructor in TypeScript?

I guess, this is somewhat basic question, but I’m failing to google this (not sure about the correct keywords), so let me ask.

Imagine a simple class with a basic constructor:

class Animal {
    name: string
    constructor(name: string) {
        this.name = name
    }
}

The problem about this is somewhat obvious: with a growing number of properties (age: number; type: AnimalType etc) one has to write those things thrice:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Animal {
    name: string
    age: number
    type: AnimalType
    // ...
    constructor(name: string, age: number, type: AnimalType) {
        this.name = name
        this.age = age
        this.type = type
        // ...
    }
}

so the constructor will get bigger and bigger, and the code is not particularly DRY. Is there some standart way to avoid this in TS? I can imagine something like

class Animal {
    @Required name: string
    @Required age: number
    @Required type: AnimalType
    // ...
    constructor(anotherParam) {
        // implicitly: this.name = name
        // implicitly: this.age = age
        // implicitly: this.type = type

        // deal with anotherParam
    }
}

but the syntax is not accurate, rather to illustrate the expected result.

The only simple solution that I’m aware of is to create an interface like this:

interface AnimalPermanentParams {
    name: string
    age: number
    type: AnimalType
}

class Animal {
    permanentParams: AnimalPermanentParams
    // ...
    constructor(permanentParams: AnimalPermanentParams, anotherParam) {
        this.permanentParams = permanentParams
        // ...
    }
}

but this has an obvious drawback of an extra layer: we have to use this.permanentParams.age instead of just this.age. So are there any sane alternatives, ideally without 3d party libs?

>Solution :

You can just declare the parameter as public (or private) and it will set the property for you.

class Animal {
    constructor(public name: string) {}
}


new Animal("abc").name

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading