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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *