Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 96 ยท Objects and Classes

Getters and Setters

Learn TypeScript getters and setters - read-only and computed properties, validation, lazy values, differing getter and setter types, accessors in interfaces and the JSON pitfall.

A property normally just stores a value. An accessor looks like a property from the outside, account.balance or account.balance = 5, but runs a function each time it is read or written. Accessors come in pairs: a getter (get) runs when the property is read, and a setter (set) runs when it is assigned. They let a class compute values on demand, validate input, keep related fields consistent and hide how data is stored, without callers writing getBalance() and setBalance() calls.

Access Modifiers and Private Fields already showed a short example. This lesson covers accessors on their own terms: the typing rules (including getters and setters with different types), the common patterns, how accessors appear in interfaces and object literals, and the surprises that catch people, such as accessors disappearing from JSON.stringify. It assumes you know classes and private fields.

Read-only and computed properties

A getter with no setter creates a read-only property. This is the most common use: a value derived from other fields, always up to date, impossible to assign by accident.

TypeScript Computed read-only properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is 12 false 3x4 (rectangle) followed by 16 true 4x4 (square). There is no stored area field to go stale: it is computed from width and height each time. TypeScript treats a property with only a getter as readonly, so the assignment in the comment is a compile-time error. Compare that with storing area as a field, where you would have to remember to update it whenever the width or height changes.

Validation in setters

A setter is the right place to protect an invariant, a rule that must always hold. Callers can write temp.celsius = -300 like any assignment, and the class decides what to do. Keep the real data in a private field so the only way to change it is through the setter.

TypeScript A setter that validates and normalizes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

You get 21.5 71, then 100 212, then Impossible temperature: -500 and finally 100. The two views of the same value (Celsius and Fahrenheit) stay consistent because only #celsius is stored. The Fahrenheit setter calls the Celsius setter, so the validation lives in one place. Note that the failed assignment leaves the old value in place: validate first, then store.

Two rules about the pair to remember:

  • Getter and setter for the same name must have the same accessibility (both public, or both private, and so on). You cannot make the getter public and the setter private on a single property.
  • A setter has no return type and cannot return a value. If you need to report failure, throw an exception (as above) or provide a separate method that returns a Result.

Getters and setters with different types

By default the setter's parameter type is the getter's return type. Since TypeScript 5.1 the two types can be completely unrelated, which is useful when the setter accepts looser input and stores something stricter. The getter's type is what readers see; the setter's type is what writers may assign.

TypeScript A setter that accepts more than the getter returns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This prints hello-typescript-world, getters-and-setters and 19. Reading s.value always yields a string, so no caller needs to narrow it, while assigning accepts string | string[]. Before TypeScript 5.1 the getter type had to be assignable to the setter type, and in 5.1 this restriction was lifted entirely. Use the feature with care: when assignment and reading disagree, s.value = x; s.value === x is no longer a safe expectation, and readers can find that surprising. Document it, as the comment does here.

Lazy values and caching

A getter can do expensive work the first time and remember the answer. Combined with a private field it makes a lazy property: nothing is computed until someone asks.

TypeScript A lazy getter that caches its result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The first line prints computations so far: 0, the second and third read the summary ({ total: 100, average: 25 } and 25), and the last prints computations at the end: 1. The cache would need to be cleared if #rows could change. Here the rows are readonly and never reassigned, so the cached value stays correct. As a rule, cache only values that depend on data that cannot change, or invalidate the cache in every method that does change that data.

Accessors in interfaces, object literals and statics

Accessors are not limited to classes. They appear in three more places.

Interfaces and type aliases describe a property. The type does not say whether it is stored or computed, so a class with a getter satisfies an interface that declares a readonly property:

TypeScript
interface HasArea {
  readonly area: number;
}

class Circle implements HasArea {
  constructor(public radius: number) {}
  get area(): number {
    return Math.PI * this.radius ** 2;
  }
}

const shapes: HasArea[] = [new Circle(1), { area: 10 }];   // a plain object works too

Object literals can contain get and set too, which is useful for small computed objects:

TypeScript
const counter = {
  count: 0,
  get next(): number {
    return ++this.count;
  },
  set reset(value: number) {
    this.count = value;
  },
};

Static accessors work the same way with the static keyword, and are handy for class-level computed values (static get version(): string). The accessor keyword from Access Modifiers is related but different: it declares a stored field with an automatic getter and setter, mainly for decorators.

Accessors can be overridden in subclasses too, but a subclass should not turn a getter-only property into a plain field or the reverse. TypeScript reports TS2610 and TS2611 for accessor/property mismatches, because that would change how the property behaves on the base class.

Pitfalls

Accessors are convenient, and they have some quirks.

Accessors live on the prototype

A getter defined in a class is stored on the class's prototype, not on each instance. Only own, enumerable properties take part in JSON.stringify, spreading ({ ...obj }) and Object.keys. Accessors are not among them:

TypeScript Accessors do not appear in JSON or spread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is Lamp ($30), {"name":"Lamp","price":30}, { name: 'Lamp', price: 30 }, [ 'name', 'price' ] and finally {"name":"Desk","price":120,"label":"Desk ($120)"}. The getter works when you read p.label, but it is missing from the serialized copy. If you need it in JSON, add a toJSON method, as shown.

Accessors should be cheap and predictable

Callers assume that reading a property is fast and has no side effects. A getter that makes a network call, a getter that changes state each time you read it (like next in the object literal above), or a setter that does heavy work are all surprising. If the work is slow or has side effects, make it a method with a verb name: load(), nextId(), refresh(). Reserve getters for cheap derived values and simple validation.

Do not name the backing field like the accessor

A getter named name that reads this.name calls itself forever and overflows the stack. Give the stored value a different name. The usual choices are a #private field (#name, shown throughout this lesson) or a TypeScript private _name. The # version is truly private at runtime; the underscore version is only a compile-time hint.

Do you need an accessor at all?

If a getter just returns a field and the setter just assigns it, with no validation, a plain public field does the same job with less code. And you can change your mind later: replacing a field with an accessor pair keeps every caller working, because they use the same property syntax. Start simple, and add accessors when you have a reason.

flowchart LR
    C["caller: temp.celsius = 25"] --> S["set celsius(value)"]
    S -- "valid" --> F["store in #celsius"]
    S -- "invalid" --> X["throw RangeError"]
    R["caller: temp.fahrenheit"] --> G["get fahrenheit()"]
    G --> F

Callers use property syntax; the class decides what happens on every read and write.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What type does TypeScript give a property that has a getter but no setter?

    A getter-only accessor is read-only. Assigning to it is a compile-time error and would throw in a class at runtime.
  2. 2. Which is allowed since TypeScript 5.1?

    Getter and setter types can now be unrelated. Accessibility must still match, setters cannot return values, and getters take no parameters.
  3. 3. Why is the getter label missing from JSON.stringify(product)?

    JSON.stringify, spread and Object.keys only see own enumerable properties. Add a toJSON method to include computed values.
  4. 4. What is wrong with "get name() { return this.name; }"?

    Reading this.name inside the getter invokes the getter again. Store the value under a different name.
  5. 5. When is a method better than a getter?

    Properties are expected to be cheap and free of side effects. Use a verb-named method for loading, refreshing or anything with effects.

Summary

  • A getter runs when a property is read, a setter when it is assigned; callers use plain property syntax.
  • A getter without a setter is a read-only, always-current computed property.
  • Setters protect invariants: validate, normalize, then store in a private field. Getter and setter share the same accessibility, and a setter cannot return a value.
  • Since TypeScript 5.1 the getter and setter may have unrelated types, for example reading a string but accepting string | string[].
  • Lazy getters can cache expensive results in a private field, as long as the underlying data cannot change.
  • Accessors can appear in interfaces (as properties), object literals and statics.
  • They live on the prototype, so JSON, spread and Object.keys do not see them; keep them cheap, and never reuse the accessor's name for its backing field.

Next: Generics