4

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?

PlayHardGoPro
  • 2,791
  • 10
  • 51
  • 90
  • 1
    You need to declare a variable out of the constructor like `private language: string`. – Vagner Wentz Aug 19 '21 at 13:10
  • 2
    Read about [classes](https://www.typescriptlang.org/docs/handbook/2/classes.html) in the [TypeScript documentation](https://www.typescriptlang.org/docs/handbook/intro.html). – axiac Aug 19 '21 at 13:37

2 Answers2

5

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'
  }
}
AleksW
  • 703
  • 3
  • 12
  • I maked the same response but I add a comment hahaha – Vagner Wentz Aug 19 '21 at 13:11
  • Thanks guys. I'll upvote both. I thought as this could be done with `javascript` I would also be able to do it in `TS`. Thanks – PlayHardGoPro Aug 19 '21 at 13:12
  • 1
    "I thought as this could be done with javascript I would also be able to do it in TS" See https://stackoverflow.com/questions/41750390/what-does-all-legal-javascript-is-legal-typescript-mean – jcalz Aug 19 '21 at 13:32
3

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'
  }
}
Thomas Smith
  • 31
  • 1
  • 4
  • 1
    See https://www.typescriptlang.org/docs/handbook/2/classes.html for more info – Thomas Smith Aug 19 '21 at 13:15
  • 2
    Just as a tip: It does not need to be above the constructor, all property declarations are called before the constructor no matter where in the class they are, having them above does make the most sense though – AleksW Aug 19 '21 at 13:16