Jon B
Jon B

Reputation: 61

Typescript let keyword and not defined type variable difference

I am new to typescript, I know the difference between let and var. But I am not able to understand for what variables we use the 'let' keyword and for what we dont.

In the code here

class ClassName{
   let num: number = 10; // Error "A Constructor, method, accessor or property expected"
   num = 10; //Works fine
}

varName: ClassName = new ClassName() // Error "Cannot assign to ClassName because it is not a variable"
let varName: ClassName = new ClassName() // Works fine

So we should use let outside classes and should'nt use inside the classes? why if so?

or there is another important difference between them?

Upvotes: 1

Views: 206

Answers (1)

tmhao2005
tmhao2005

Reputation: 17514

Here's the inline explanations for your confusions:

class ClassName {
  // In a class scope you can just able to declare its member only
  // which means you can't declare a variable starting with `var/let/const` here
  // Each member can only start with visibility keyword `public/private/protected/static`
  // default is `public`, that's why `num = 10` works fine
}

varName: ClassName = new ClassName() is all about wrong syntax since varName is not a valid keyword.

let varName: ClassName = new ClassName() of course is valid syntax saying variable of varName is assigned an instance of ClassName with the same type ClassName.

Upvotes: 2

Related Questions