DEV Community

Discussion on: TypeScript is more than you think

Collapse
 
dankwansere profile image
Dankwansere

Well written article, I enjoyed reading this.

But there is an error or misconception you made in this article that I should point out.
You stated the following

type X = 1; /* is TSts🟦 equivalent for JS🟨 : */ const X = 1;

Declaring "type X = 1" in typescript is NOT equivalent to "const x = 1" in Javascript.

The reason for this is because in Typescript, declaring a variable with a type only, prevents you from changing the type of the variable thereafter, but it does not prevent you from assigning a different type of value to that variable.
For example if I do the following in Typescript
let age:number = 5
I can later set age to a different number without any repercussions. But I will not be able to assign a string to age.

As for const (which works the same in JS and TS) once you declare a variable with const you cannot re-declare it to something else even if it's of the same type. For example If I was to do

const age:number = 5(typescript)
or const x = 5(Javascript)
I cannot re-declare age or x to a different number later. You would receive a compile time error in Typescript or a Runtime Error in Javascript. Const keyword is more equivalent to the "final" keyword in Java