0

I searched extensively but couldn't find any satisfactory answer as to why there are fields in classes of typescript

class car{
   name:string //Whats the use of this when we already have properties in constructor

constructor(name:string){
  this.name:name;
  }
}
  • If you don't declare it, it doesn't exist. – CodeCaster Aug 19 '17 at 16:15
  • Possible duplicate of [TypeScript private members](https://stackoverflow.com/questions/12713659/typescript-private-members) – CodeCaster Aug 19 '17 at 16:15
  • 1
    but we define them in the constructor function.right? –  Aug 19 '17 at 16:16
  • No, you _initialize_ them in the constructor. For that to work, they have to exist. Undeclared variables don't exist. – CodeCaster Aug 19 '17 at 16:16
  • we dont do that in es5. what was the need for that in es6 or typescript –  Aug 19 '17 at 16:17
  • you can use `interface` for field types. – Aravind Aug 19 '17 at 16:19
  • @coder360 es5 doesn't have it but es6 does. It's much more clearer now that we explicitly declare the properties. That's the whole point of using typescript isn't it? So that you get IntelliSense and don't misspell it like 'Name'? If you look at the js of this class, it won't have a name property, unless you initialize it while declaring or in the constructor. – adiga Aug 19 '17 at 16:22
  • so other than avoiding mistakes is there any other use of it –  Aug 19 '17 at 16:27

0 Answers0