PlayHardGoPro
PlayHardGoPro

Reputation: 2923

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?

Upvotes: 4

Views: 1243

Answers (2)

Thomas Smith
Thomas Smith

Reputation: 31

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'
  }
}

Upvotes: 3

AleksW
AleksW

Reputation: 713

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'
  }
}

Upvotes: 5

Related Questions