Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cant we use the let keyword inside a class in typescript

I am new to TypeScript. I want to know why we can't use the let keyword for variable declaration inside a class as below. Thanks in advance.

class Greeter {
    let greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

let greeter = new Greeter("world");
console.log(greeter.greet())
like image 578
user3256451 Avatar asked Dec 09 '17 19:12

user3256451


2 Answers

I believe your question is why can't we use let key word...

In TypeScript:

This is merely a syntactic choice I suppose, but class properties do not need a keyword. You can optionally add a public keyword or if you want the class property to be private for the type you can use the private keyword:

class Greeter {
  greeting: string;
  // or
  public greeting: string;
  //alternatively
  private greeting: string;

This is just to define the property for the purposes of the type. Later, when you do:

const greeter = new Greeter;

Now you will be able to use greeter.greeting and all string methods and TypeScript will transpile successfully. If greeting were not declared you would get an error when attempting to transpile

Property 'greeting' does not exist on type 'Greeter'

In JavaScript:

There is currently no way to declare class properties in JavaScript at all. It's intentionally not supported.

like image 50
Explosion Pills Avatar answered Nov 15 '22 08:11

Explosion Pills


Because it is not a keyword in that context. And given the purpose of let, I'm not sure it would ever make sense for it to be a keyword there -- it is used to restrict the scope of a variable.

Class properties (in languages that support them) are naturally restricted to the class, explicitly using the same syntax doesn't seem beneficial.

In particular, it works against how properties are currently added (assigned in the constructor), and causing confusing about what the scope actually is.

like image 20
jmoreno Avatar answered Nov 15 '22 08:11

jmoreno