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())
I believe your question is why can't we use let key word...
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'
There is currently no way to declare class properties in JavaScript at all. It's intentionally not supported.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With