ProgramGuru

Getters and Setters

Understand Getters and Setters

Getters and setters present methods through property-style access. A getter computes or retrieves a value; a setter handles assignments.

What you will learn: the purpose of getters and setters, the rules TypeScript checks, and what its JavaScript behavior looks like in a runnable example.

What you’ll learn

  • Explain how getters and setters works and where its type rules apply.
  • Predict the exact output of the getters and setters example.
  • Diagnose a common issue: Do not write a setter that assigns the same accessor recursively, such as this.

Build the mental model

Use accessors to validate invariants or derive values, not simply to hide every ordinary field. A setter still executes JavaScript logic at runtime, and it can throw when the supplied value is invalid.

Key distinction: TypeScript checks the declared types during development; emitted JavaScript carries out the value-level operation at runtime. A type declaration alone never validates untrusted runtime input.

See the relationship

Read this illustration from the first labeled part to the last. Compare it with the example and identify which parts are type checks and which parts run in JavaScript.

Getters and Setters: explained visuallySet °F = 212 → Store °C = 100 → Get °F = 212Set °F = 212Store °C = 100Get °F = 212Follow the values through the operation
Getters and Setters: Set °F = 212 → Store °C = 100 → Get °F = 212.

Run the complete TypeScript example

This self-contained example uses fixed values, so it runs without reading input or depending on an external service. Paste it into the TypeScript Playground or save it as main.ts.

TypeScript program

class Thermometer {
  private celsius = 0;
  get fahrenheit(): number { return this.celsius * 9 / 5 + 32; }
  set fahrenheit(value: number) { this.celsius = (value - 32) * 5 / 9; }
}
const t = new Thermometer();
t.fahrenheit = 212;
console.log(t.fahrenheit);
t.fahrenheit = 32;
console.log(t.fahrenheit);

Verified output

212
32

Run locally: npx tsc --strict --target es2022 --module commonjs main.ts, then node main.js. For projects with a tsconfig.json, build using that configuration instead.

Trace every important step

Assigning 212 calls the setter and stores 100 degrees Celsius. The getter converts back to 212. Assigning 32 stores zero Celsius and the next getter returns 32.

Check each step: identify the input values, follow the JavaScript operation in execution order, and match the final expression with the exact output shown. An annotation can reject invalid source before execution, but does not change the value printed.

Avoid these common mistakes

Do not write a setter that assigns the same accessor recursively, such as this.fahrenheit = value inside set fahrenheit; use separate backing state.

How to debug: reproduce the issue in a minimal example. For compiler errors, inspect the inferred and declared types; for a runtime surprise, log the actual values and follow their references or branches.

Practice and experiment

Add a celsius getter so you can inspect the backing temperature after assignments.

Practice routine: predict the result on paper, edit one part of the code, compile under --strict, run the JavaScript, and explain whether TypeScript caught an error or JavaScript simply behaved differently.

Check your understanding

What runs when t.fahrenheit = 212 is executed?
Choose one answer. You can try again.

Answer and explanation

The setter function associated with fahrenheit.

Getters and setters present methods through property-style access. A getter computes or retrieves a value; a setter handles assignments.

Review the key idea

Getters and Setters: Getters and setters present methods through property-style access.

Assigning 212 calls the setter and stores 100 degrees Celsius. The getter converts back to 212. Assigning 32 stores zero Celsius and the next getter returns 32.

Before continuing, explain one valid use case, one common pitfall, and the separation between compile-time checking and runtime behavior for this feature.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Static Properties and Methods →