Initialize a Typescript class property once

3 weeks ago 11
ARTICLE AD BOX

Let's say I have a class with many parameters. In Typescript, this is how the class is created:

class ClassName { private para1: string para2: boolean para3: number = 6 protected readonly para4: number = 9 private para5: boolean = true private readonly para6: "LiteralString" | number = "LiteralString" constructor( para1: string, para2: boolean, para3?: number, para4?: number, para5?: boolean, para6?: "LiteralString" | number ) { this.para1 = para1 this.para2 = para2 if (para3) this.para3 = para3 if (para4) this.para4 = para4 if (para5) this.para5 = para5 if (para6) this.para6 = para6 } myMethod() { // Just a method } myMethod2() { // Another method } }

As you can see, each parameter has to be defined 4-5 times and in 3 places each: the class field, the class constructor parameters and the class constructor itself.

This code is very messy. How can I improve the code and make it DRY (Don't Repeat Yourself) so that I only have to define each field once and make it function the same?

Note that I prefer not to lose any functionality from the code above. For example I want to still be able to use public, private, protected and readonly modifiers.

Solution in other programming languages

Python

In python, there is an easy solution to this, and it's by using data classes from dataclasses module:

from typing import Literal from dataclasses import dataclass # Before class ClassName: def __init__( para1: str, para2: bool, para3: int = 6, para4: int = 9, para5: bool = True, para6: Literal["LiteralString"] | int = "LiteralString" ): this.para1 = para1 this.para2 = para2 this.para3 = para3 this.para4 = para4 this.para5 = para5 this.para6 = para6 # After @dataclass class ClassName: para1: str para2: bool para3: int = 6 para4: int = 9 para5: bool = True para6: Literal["LiteralString"] | int = "LiteralString"
Read Entire Article