TypeScript example

How to use getters and setters in TypeScript

8 min read Updated Nov 2026 Runs in an isolated runtime
Quick answer

Write a get and a set accessor with the same name and keep the value in a field with a different name: #name = ""; get name(): string { return this.#name; } set name(value: string) { this.#name = value; }. Callers use it like a field, user.name = "Ada", and the setter runs. Leave out the set and TypeScript treats the property as read-only.

Accessors let a class look like it has plain properties while running code on every read and write: validate a value before storing it, normalize it, or compute it from other fields. The get and set syntax is JavaScript's; TypeScript adds the types, makes a getter-only property read-only at compile time, and lets the setter accept a wider type than the getter returns. The sections below cover the get/set pair, read-only getters, separate get and set types, the two pitfalls everyone hits (a setter that calls itself, and JSON.stringify skipping accessors), field initializers and the "object initializer" constructor, and accessors in interfaces and object literals. Each example runs on this page: hit Run, then edit the code and run it again.

1A get and set pair with a private fieldRecommended

Declare the value in an ES private field (#celsius), then a get that returns it and a set that checks the new value before storing it. Annotate the getter's return type and the setter's parameter; a setter has no return type, not even void (set x(v: number): void is error TS1095). An accessor doesn't need a field of its own: fahrenheit below converts from #celsius both ways, and its setter goes through the celsius setter, so the check lives in one place.

temperature.ts
class Temperature {
    // The value lives in a private field; the accessors wrap it.
    #celsius = 0;

    get celsius(): number {
        return this.#celsius;
    }

    set celsius(value: number) {
        // A setter can check the value before it stores it.
        if (value < -273.15) {
            throw new RangeError(`${value} °C is below absolute zero`);
        }
        this.#celsius = value;
    }

    // A computed property: no field of its own, it converts on the fly.
    get fahrenheit(): number {
        return (this.#celsius * 9) / 5 + 32;
    }

    set fahrenheit(value: number) {
        this.celsius = ((value - 32) * 5) / 9; // reuses the check above
    }
}

const t = new Temperature();
t.celsius = 25; // runs the setter: no parentheses, it reads like a field
console.log(t.celsius, t.fahrenheit);

t.fahrenheit = 212;
console.log(t.celsius);

try {
    t.celsius = -300;
} catch (err) {
    console.log(err instanceof Error ? err.message : err);
}
console.log(t.celsius); // the bad value was never stored

Output

It prints 25 77, then 100 after setting 212 °F. The bad value throws -300 °C is below absolute zero and the last line still prints 100, because the setter threw before it stored anything. The caller never sees the difference between a field and an accessor, which is the point: you can start with a public field and turn it into a get/set pair later without changing a single caller.

2A getter without a setter is read-only

Write only the get and TypeScript infers the property as readonly. Reading it works everywhere; assigning to it is a compile error, so the mistake never reaches runtime. This embed fails on purpose: the type error on the last line stops the run before anything executes, including the console.log above it.

read-only.ts
class Circle {
    constructor(public radius: number) {}

    // A getter with no setter: TypeScript types area as read-only.
    get area(): number {
        return Math.PI * this.radius ** 2;
    }
}

const c = new Circle(2);
console.log(c.area.toFixed(2));

c.radius = 3; // fine: radius is a plain public field
c.area = 30; // error: there is no setter to call

Output

The compiler reports error TS2540: Cannot assign to 'area' because it is a read-only property. Delete the last line and the program prints 12.57, then 28.27 after the radius changes: a getter recomputes on every read, unlike a readonly field, which is fixed once the constructor has run. For values that never change at all, see define class constants.

3Different types for get and set

The setter's parameter may be wider than the getter's return type. Here width accepts number | string and always reads back as a number, so callers can pass "120px" and still do arithmetic on the result without a cast. TypeScript 4.3 added this as long as the get type is assignable to the set type; since 5.1 the two types can be unrelated, as long as both accessors carry an explicit annotation.

set-type.ts
class Box {
    #width = 0;

    // The getter always returns a number...
    get width(): number {
        return this.#width;
    }

    // ...while the setter also accepts CSS-style strings such as "120px".
    set width(value: number | string) {
        const n = typeof value === "string" ? parseFloat(value) : value;
        this.#width = Number.isFinite(n) ? n : 0;
    }
}

const box = new Box();
box.width = "120px";
console.log(box.width, typeof box.width);

box.width = 80;
console.log(box.width + 20); // a number, so this is arithmetic, not "8020"

box.width = "wide";
console.log(box.width);

Output

It prints 120 number, then 100 (a sum, not the string "8020"), then 0 for a string that isn't a number. Inside the setter, typeof value === "string" narrows the union, so each branch gets the right type. The DOM types use the same trick: element.style reads back as a CSSStyleDeclaration but also accepts a string of CSS.

4Pitfalls: a setter that calls itself, and JSON

The most common accessor bug: inside set name, this.name = value doesn't write a field, it calls the same setter again, until the stack runs out. TypeScript doesn't flag it, because the code is valid. Store the value under a different name: an ES private field such as #name, or a private _name field as older code bases do. The second surprise is serialization: accessors live on the class's prototype, not on the object, so JSON.stringify and Object.keys don't see them.

pitfalls.ts
// Pitfall 1: the accessor and its field share a name.
class Broken {
    get name(): string {
        return this.name; // calls this getter again...
    }
    set name(value: string) {
        this.name = value; // ...and this calls this setter again, forever
    }
}

try {
    new Broken().name = "Ada";
} catch (err) {
    console.log(err instanceof Error ? `${err.name}: ${err.message}` : err);
}

// The fix: store the value under another name (#name or _name).
class User {
    #name = "";
    private _role = "admin";

    get name(): string {
        return this.#name;
    }
    set name(value: string) {
        this.#name = value.trim();
    }

    get role(): string {
        return this._role;
    }
}

const user = new User();
user.name = "  Ada ";
console.log(`[${user.name}]`);

// Pitfall 2: accessors live on the prototype, not on the object, so
// JSON.stringify and Object.keys skip them; #name is skipped too, and
// TypeScript's private _role is an ordinary property at runtime.
console.log(JSON.stringify(user));
console.log(Object.keys(user));

Output

The broken class throws RangeError: Maximum call stack size exceeded; the fixed one prints [Ada] with the spaces trimmed. Then JSON.stringify(user) gives {"_role":"admin"} and Object.keys gives [ '_role' ]: neither accessor appears, the #name field is invisible, and TypeScript's private is only a compile-time check, so _role is an ordinary property at runtime. To control the JSON, add a toJSON() method that returns the shape you want.

5Field initializers and an object initializer

A field can take its default where it's declared (owner = "unknown"), and a parameter property (constructor(public x: number)) declares and assigns a field in one go. TypeScript has no C#-style object initializer, but a constructor that takes Partial<Account> and calls Object.assign(this, init) comes close: callers pass any subset of the properties, and the field initializers, which run before the constructor body, fill the rest. Object.assign assigns, so it goes through your setters.

initializers.ts
// Parameter properties: "public x" declares the field and assigns it.
class Point {
    constructor(public x: number, public y: number) {}
}

class Account {
    // Field initializers run first, before the constructor body.
    owner = "unknown";
    tags: string[] = [];
    #email = "";

    // Like a C# object initializer: pass any subset of the fields.
    constructor(init?: Partial<Account>) {
        Object.assign(this, init);
    }

    get email(): string {
        return this.#email;
    }
    set email(value: string) {
        this.#email = value.toLowerCase();
    }
}

const p = new Point(3, 4);
console.log(p.x, p.y);

const a = new Account({ owner: "Ada", email: "[email protected]" });
console.log(a.owner, a.email, a.tags.length);

// Defaults stay where init leaves a gap; Object.assign ran the setter.
const b = new Account();
console.log(b.owner, JSON.stringify(b.email));

Output

It prints 3 4, then Ada [email protected] 0 (the setter lowercased the email), then unknown "" for an account built with no argument. Declare a field with neither an initializer nor a constructor assignment, such as owner: string;, and with strict on (as in most projects) the compiler reports error TS2564: Property 'owner' has no initializer and is not definitely assigned in the constructor. This page's compiler runs without strict, so it stays quiet. Give the field a default, assign it in the constructor, or write owner!: string; when something else sets it. One trap with Object.assign in a base class: a subclass that redeclares the fields (name: string;) resets them to undefined after super() returns, so p.name and p.age print undefined undefined. Write declare name: string; in the subclass and they print Ada 36.

6Accessors in interfaces, object literals and static members

An interface describes what callers can do, not how the class stores it, so readonly area: number is satisfied by a field or by a getter. Since TypeScript 4.3 an interface can also spell out get and set signatures. Object literals take the same get/set syntax as classes, and a static accessor belongs to the class itself, here a read-only counter over a private static field.

interfaces.ts
// An interface can't tell a field from a getter: readonly area is
// satisfied by either. TypeScript 4.3+ also accepts get/set signatures.
interface Shape {
    readonly area: number;
    get label(): string;
}

class Square implements Shape {
    constructor(private side: number) {}

    get area(): number {
        return this.side ** 2;
    }
    get label(): string {
        return `square ${this.side}`;
    }

    // Static accessors belong to the class itself.
    static #created = 0;
    static get created(): number {
        return Square.#created;
    }
    static make(side: number): Square {
        Square.#created++;
        return new Square(side);
    }
}

// A plain object literal can have accessors too.
const plain: Shape = {
    area: 6,
    get label(): string {
        return `plain ${this.area}`;
    },
};

const shapes: Shape[] = [Square.make(3), Square.make(5), plain];
for (const s of shapes) {
    console.log(s.label, s.area);
}
console.log("squares made:", Square.created);

Output

It prints square 3 9, square 5 25 and plain 6 6, then squares made: 2. Code typed against Shape reads s.area the same way whether it hits a getter or a field, and Square.created can be read but not assigned from outside, because it has no setter.

7Which should you use?

MethodRuns code on accessCallers can assignBest for
name = ""NoYesThe default: plain data, no rules
readonly nameNoNo (compile-time)Set once in the constructor
get name() onlyOn readNo (compile-time)Computed or derived values
get + set with #nameOn read and writeYes, through the setterValidation, normalizing, side effects
getName() / setName()On every callVia the methodWork that is slow or needs arguments

Frequently asked questions

Should I use getters and setters or public fields in TypeScript?

Start with public fields. Unlike Java, TypeScript does not need accessors up front to keep the option open: a get/set pair has the same call syntax as a field, so you can turn name into accessors later without touching any caller. Add them when reading or writing has to run code: validation, normalizing, a computed value or a change notification. Prefer a getName() method when the work is slow or takes arguments, because property syntax suggests a cheap read.

Why does my setter throw "Maximum call stack size exceeded"?

Because the setter assigns to its own name: inside set name(value), this.name = value calls set name again, endlessly, and Node stops with RangeError: Maximum call stack size exceeded. A getter that returns this.name does the same. Keep the value in a field with another name, such as #name or private _name, and read and write that field inside the accessors.

Why does JSON.stringify skip my getters?

JSON.stringify serializes an object's own enumerable properties, and class accessors are defined on the prototype, so they are not included; #private fields are never included either. Add a toJSON() method that returns the shape you want, for example return { name: this.name, email: this.email };, and JSON.stringify(user) gives {"name":"Ada","email":"[email protected]"}.

How do I fix "Property has no initializer and is not definitely assigned in the constructor"?

That is error TS2564, reported with strict (strictPropertyInitialization) on for a field such as owner: string; that nothing assigns. Give it a default (owner = ""), assign it in the constructor, make it optional (owner?: string) if it can really be missing, or add a definite assignment assertion (owner!: string;) when a framework or an init() method sets it before use. The ! only silences the check; it does not set a value.

Can a getter and a setter have different types?

Yes. Since TypeScript 4.3 the setter can accept a wider type than the getter returns, such as set width(value: number | string) with get width(): number. Since TypeScript 5.1 the two types may be unrelated, provided both accessors have explicit type annotations. Older versions required one type for both.

Should the backing field be #name or private _name?

Prefer #name in new code. TypeScript's private is checked only at compile time: at runtime _name is an ordinary property that shows up in Object.keys, JSON.stringify and a for...in loop, and any JavaScript caller can change it. A #name field is private in the running program too. Use private _name when you need the field visible to a serializer or you target code that predates ES2022 private fields.

Run it yourself

Open any of these in the full TypeScript editor to tweak, run and share.

TypeScript playground