- Mastering TypeScript 3
- Nathan Rozentals
- 132字
- 2021-07-02 12:42:44
Const values
The TypeScript language also allows us to define a variable as a constant, by using the const keyword. If a variable has been marked as const, then its value can only be set when the variable is defined, and cannot be modified afterward. Consider the following code:
const constValue = "test"; constValue = "updated";
Here, we have defined a variable named constValue, and indicated that it cannot be changed by using the const keyword. Attempting to compile this code will result in the following compile error:
error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property.
This error is, in fact, generated for the second line of code, where we are attempting to modify the value of the constValue variable to the string "updated".