Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating property inside constructor with Typescript

I have a javascript code that works perfectly:

class myController {
   constructor () {
      this.language = 'english'
   }
}

BUT when I try to do the same with Typescript

export default class myController {
  constructor () {
    this.language = 'english'
  }
}

It gives me the following error:

Property 'language' does not exist on type 'myController'.ts(2339)

Why exactly this happen when trying to create a property for myController?
What would be the right way to do so?

like image 852
Jupirao Bolado Avatar asked Sep 05 '25 16:09

Jupirao Bolado


2 Answers

Because you are trying to set a property which does not exist in the class as it says, declare it somewhere in the class before you try set it, i.e:

export default class myController {
  private language: string;
  constructor () {
    this.language = 'english'
  }
}
like image 59
AleksW Avatar answered Sep 07 '25 08:09

AleksW


It needs to be declared as a Property on the type (typically before the constructor):

export default class myController {
  language: string;
  constructor () {
    this.language = 'english'
  }
}
like image 22
Thomas Smith Avatar answered Sep 07 '25 08:09

Thomas Smith