call a setter on an instance of a class in typescript

To call a setter on an instance of a class in TypeScript, you simply access the property as if it were a regular property and assign it a value using the setter. Here's an example:

index.ts
class Person {
  private _name: string;

  set name(name: string) {
    this._name = name;
  }

  get name() {
    return this._name;
  }
}

const john = new Person();
john.name = 'John Smith'; // Calling the setter
console.log(john.name); // Output: John Smith
262 chars
16 lines

In this example, we define a Person class with a private _name property and a name accessor with a setter and getter. To call the setter, we simply access the name property on an instance of the Person class and assign it a value.

Note that if the property being accessed has only a getter defined, attempting to assign a value to it will result in a TypeError being thrown at runtime.

gistlibby LogSnag