{

How to add final to variables and methods in typescript?


Java provides the final keyword to variables, methods, and classes to p

Does typescript have the final keyword? Typescript does not have a final keyword, But we can make it using various ways. One way is using a readonly keyword to variables, and another way using a decorator that is not writable.

You can also check Typescript classes and objects

Typescript final variable

The final keyword in variables is only assigned once during the constructor.

final variables added with the readonly keyword. initialize the value once and readonly later. readonly is introduced in that allows to initialization of the variable at declaration or constructor.

In the below example,

  • id, name, and company are members of the Employee class
  • constructor contains id with readonly, which means it assigns the value one time during object creation. It throws Compilation Error `Cannot assign to ‘id’ because it is a read-only property. Other fields’ names and companies can be assigned many times.

Here is a typescript final variable example.

class Employee {
  constructor(
    readonly id: number,
    public name: String,
    public company: String
  ) {}
}

let emp: Employee = new Employee(1, "John", "abc corp");

emp.id = 12; //Error Cannot assign to 'id' because it is a read-only property.(2540)

emp.name = "john";
emp.company = "z corp";

console.log(emp.id, emp.name, emp.company);

Typescript has a const keyword for variables, It does not apply to class member variables.

Typescript final methods

methods with final do not override during extended inheritance hierarchy.

In the below example,

  • Create a final decorator that does not allow writable, ie. readonly
  • Superclass has a method that is annotated with @final decorator.
  • Extend the superclass and override the final method
  • It does not throw at compile time.
  • At runtime, It throws Cannot assign to read only property ‘meow’ of object ‘#’
  • Subclasses do not override the final methods in the parent class Here is a Typescript final methods example
function final(
  target: Object,
  key: string | symbol,
  descriptor: PropertyDescriptor
) {
  descriptor.writable = false;
}

class Animal {
  eat() {
    console.log("Animal Eat");
  }
  @final
  meow() {
    console.log("Animal Eat");
  }
}
class Lion extends Animal {
  eat() {
    console.log("Lion Eating");
  }
  meow() {
    console.log("Not Implemented");
  }
}

let lion = new Lion();
lion.eat(); // works
lion.meow(); // does not works, Runtimeerror

Conclusion

Learned how to add final keyword behavior in typescript to variables and methods.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.