basarat / typescript-book

:books: The definitive guide to TypeScript and possibly the best TypeScript book :book:. Free and Open Source 🌹
https://basarat.gitbook.io/typescript/
Other
20.88k stars 2.56k forks source link

[ FEATURE REQUEST ] TypeScript could fix broken "const" variable declaration in JavaScript #647

Open TheCelavi opened 3 years ago

TheCelavi commented 3 years ago

In all programming languages, "const" means "a design time constant" which is immutable. But not for JavaScript, it is a variable that is a readonly within context. It is a "readonly" - not a constant.

Type script should easily "fix" this allowing us to use "readonly" for variable declaration.

Wrong:

(a: number) => {
       const b: number = a || 1; // this is not a constant, this is readonly variable
}

Good:

(a: number) => {
       readonly b: number = a || 1; // this makes sense
}

And transpiler should be able to easily just rename from "readonly b" to "const b" in JavaScript version of the code.

I as a developer with knowledge of other programming languages have so much issue with abuse of "const" keyword in JavaScript => and TypeScript, yet again has an opportunity to fix broken language.

Pretty please?

Thank you!

orta commented 3 years ago

TypeScript's design goals are to not make changes like this: https://www.youtube.com/watch?v=8qm49TyMUPI&t=1s

TheCelavi commented 3 years ago

Ok, that is 30 minutes of video, if you had time to record it, I will find time to watch it in full, thank you.

In general, I understand your point.

But isn't a "readonly" for class property a syntactic sugar added by TypeScript, adding more than just plain strict typings? Seams that adding support for "readonly" variables is kinda next natural step forward?