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?

2
  • 1
    You need to declare a variable out of the constructor like private language: string. Commented Aug 19, 2021 at 13:10
  • 2
    Read about classes in the TypeScript documentation. Commented Aug 19, 2021 at 13:37

2 Answers 2

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'
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I maked the same response but I add a comment hahaha
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
"I thought as this could be done with javascript I would also be able to do it in TS" See stackoverflow.com/questions/41750390/…
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'
  }
}

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.