Search code examples
javascripttypescriptconstructortslinttsconfig

Using this keyword on constructor's parameters


name: string;

constructor(private value: string) {
  this.name = value;
  // or 
  this.name = this.value;
}

Which of these options are better. Why have I an option to use this prefix on value? Is it valid to use this keyword on constructor's parameters?

I've used an noUnusedParameters, noUnusedLocals in tsconfig and tslint to make sure that there is no unused variables in my program. Unfortunately tslint reports constructor's parameters if there is no this before them (marks them as unused which is weird).


Solution

  • You can use this.value because you are assigning it when you declare it in the constructor with an access modifier as private value: string.

    If you do not intend to use value in other functions, it is better to just inject it, without giving it and access modifier.

    name: string;
    
    constructor(value: string) {
      this.name = value;
    }