What is the correct keyword or syntax to set a value in the setter, using the TypeScript getter and setter approach?

How do I create a getter and setter method for a property in TypeScript?

I’m trying to create get and set methods for a property:

private _name: string;

Name() {
    get {
        return this._name;
    }
    set {
        this._name = ???;
    }
}

What is the correct keyword or syntax to set a value in the setter, using the TypeScript getter and setter approach?

Hi

Use Getter and Setter with Property Syntax: In TypeScript, you can use the get and set syntax directly on a class property instead of defining them as methods.

This makes the getter and setter more concise and clear. For instance, use the typescript getter approach to define the getter and setter in the class body.

class Person {
  private _name: string;

  get Name(): string {
    return this._name;
  }

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

I hope this was helpful :slight_smile:

Alternatively, you can define the getter and setter as methods, but use the typescript getter terminology to clarify your intention. This is less common in TypeScript but still a valid approach.

class Person {
  private _name: string;

  Name() {
    return {
      get: () => this._name,
      set: (value: string) => { this._name = value; }
    };
  }
}

If you want to use a traditional method-like getter and setter but with property syntax, you can explicitly define them in the constructor or as class fields.

This can be useful when you need additional logic inside your typescript getter methods.

class Person {
  private _name: string;

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

  get Name(): string {
    return this._name;
  }

  set Name(value: string) {
    if (value.length > 0) {
      this._name = value;
    }
  }
}