Categories
TypeScript Answers

How to make a variable final in TypeScript?

Spread the love

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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.