Ilja
Ilja

Reputation: 46547

A way to clean up class constructor in TypeScript?

At the moment I am defining my class constructors in the following way

class MyClass {

  routerStore: RouterStore
  characterStore: CharacterStore
  characterPrivateStore: CharacterPrivateStore

  constructor(
    routerStore: RouterStore,
    characterStore: CharacterStore,
    characterPrivateStore: CharacterPrivateStore
  ) {
    super()
    this.routerStore = routerStore
    this.characterStore = characterStore
    this.characterPrivateStore = characterPrivateStore
  }
}

This feels verbose and repetitive to me. Given that TypeScript takes advantage of some latest JavaScript proposals I wanted to ask if it is possible to clean this up somehow?

Upvotes: 2

Views: 880

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250366

You can add an access modifier to the constructorparameter. This will make the parameter also a class field that will be initialized with the value of the parameter.

class MyClass {


   constructor(
       public routerStore: RouterStore,
       public characterStore: CharacterStore,
       public characterPrivateStore: CharacterPrivateStore
    ) {
       super()
   }
}

You can also use Object.assign declare the fields on the class and use a mapped type to extract just the field keys (exclude the methods):

type JustFieldKeys<T> = { [P in keyof T] : T[P] extends Function ? never : P }[keyof T] 
class MyClass {

    public routerStore!: RouterStore,
    public characterStore!: CharacterStore,
    public characterPrivateStore!: CharacterPrivateStore
    constructor(params: Pick<MyClass, JustFieldKeys<MyClass>>) {
        Object.assign(this, params);
    }
}
new MyClass({
    characterPrivateStore: null,
    characterStore: null,
    routerStore: null
})

Upvotes: 3

Related Questions