Sometimes, we want to make a variable final in TypeScript.
In this article, we’ll look at how to make a variable final in TypeScript.
How to make a variable final in TypeScript?
To make a variable final in TypeScript, we can use the readonly
keyword.
For instance, we write
class Foo {
readonly bar = 1;
readonly baz: string;
constructor() {
this.baz = "hello";
}
}
to make the bar
and baz
variables readonly
.
This means we can’t assign an new value to the variables after they’ve been assigned a value.
Conclusion
To make a variable final in TypeScript, we can use the readonly
keyword.