02 / 03

What are getter and setter functions?

Difficulty: 3/10
accessors, encapsulation, validation
  1. 1

    getter: This method comes when you want to access any property of an object. A getter is also called an accessor.

  2. 2

    setter: This method comes when you want to change any property of an object. A setter is also known as a mutator.

javascript

Scenario Questions

0-2 years experience

  1. 1We have a simple class `User` with a private `_email` field. How would you expose it using a getter and a setter in TypeScript, and what would happen if you try to assign a value directly to `email`?
  2. 2If you add a getter to a property that already has a public field, how does TypeScript treat reads of that property at runtime?

2-5 years experience

  1. 1You’re adding a `price` setter to a `Product` class that should reject negative values. After deploying, some orders are failing with `price` being `NaN`. Walk me through how you would debug this issue.
  2. 2When refactoring a legacy JavaScript module to TypeScript, you decide to replace direct property access with getters/setters for `config`. What trade‑offs do you consider regarding performance and API compatibility?

5-8 years experience

  1. 1Our front‑end library exposes a `Theme` object with many nested properties. We want to add getters/setters to enforce validation and lazy loading. How would you design this to avoid excessive runtime overhead and keep tree‑shaking effective?
  2. 2A micro‑service serializes objects to JSON before sending them over the wire. Introducing getters changes the output. How would you ensure the serialized shape stays stable without breaking existing clients?

8+ years experience

  1. 1The company is migrating a massive codebase from plain objects to class‑based models with accessors for all public fields. What architectural guidelines would you set to manage the migration, avoid breaking changes, and keep compile‑time safety?
  2. 2Cross‑team, some services rely on reflection to auto‑generate API docs from TypeScript classes. Introducing getters/setters can hide fields. How would you standardize the use of accessors so documentation generation remains accurate?

Follow-up Questions

  • What would happen if you made the setter private?
  • How does TypeScript emit getters and setters in the compiled JavaScript?
  • Can a getter introduce side effects that callers might not expect?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.