| by Arround The Web | No comments

Explain TypeScript const vs readonly Utility Type

Typescript uses the “const” keyword and “readonly” utility type as data types for the initialization of variables or properties. According to their name and functionalities, both these data types are quite different from each other but sometimes the user gets confused when they are used in the same source code. This guide explains the difference between TypeScript “const” keyword and the “readonly” utility type.

First, look at the basics of the “const” and “readonly” utility types.

What is TypeScript “const” Keyword?

The “const” keyword specifies that the given variable is constant which means that its value cannot be modified once it has been assigned. It treats the specified variable as a constant at compile time.

Let’s see it practically with the help of the given code.

Code

Copy the code lines in the “.ts” file of the TypeScript project:

const a = 100;
a = 50;
console.log(a);

 
In the above-stated code lines:

    • The “const” keyword initializes “a” as a constant variable.
    • Next, the constant “a” variable value is modified.
    • Lastly, the “log()” method displays the “a” variable value.


It can be seen that the editor also generates an error on modifying the constant “a” variable value after its initialization.

Output

tsc main.ts // Compile .ts File
node main.js // Run .js File

 

It is observed that during compilation an error is generated that specifies the “a” variable value cannot be changed because it is a constant.

What is Typescript readonly Utility Type?

Now move on to the difference between the TypeScript “const” keyword and the “readonly” utility type.

Explain TypeScript “const” vs “readonly” Utility Type

The key differences between the TypeScript “const” keyword and the “readonly” utility type are stated here:

    • Working: The “const” keyword indicates that the “variable” value cannot be modified after initialization whereas the “readonly” utility type specifies that the “property/variable” value cannot be changed once it has been set.
    • Usage: The “const” keyword is used for only variables to make them constant. On the other hand, the “readonly” utility type is utilized for “properties and variables” that are parts of an interface or object.
    • Modification: The “const” variables cannot be modified at all while the “readonly” properties can be modified runtime with the help of the JavaScript methods.

Conclusion

In TypeScript, the “const” keyword and “readonly” utility type differ from each other on the basis of “working”, “usage”, and the “modification” factors. The main difference between them is that the “const” only makes the variable constant whereas the “readonly” makes both variables and properties constant. This guide deeply explained TypeScript “const” vs “readonly” utility type.

Share Button

Source: linuxhint.com

Leave a Reply