TypeScript Tutorial

TypeScript Getters and Setters

get and set look like fields from the outside. Inside they run code, so you can validate.

A field that is really a call

From the caller’s side, tank.percent looks like a property. If that property is defined withget and set, reading it runs a function and writing it runs a function. You can reject a bad value, clamp a range, or compute from private fields.

C++ uses a destructor to run code when an object dies, and named getX / setX methods for access. TypeScript’s get / set are the access half: they run while the object lives, at each read or write. Keep the real data private.

get looks like a read

Write get name() with no parameter. Return the value callers should see. They writep.name, not p.name(). A missing pair of parentheses is correct.

Example

class Player {
  private label: string;

  constructor(label: string) {
    this.label = label;
  }

  get name(): string {
    return this.label;
  }
}

const p = new Player("Ada");
console.log(p.name);

Output is Ada. p.label does not compile: the field is private. The getter is the public read path.

Compile this in /typescript/try. Add parentheses on purpose:p.name() is a type error because name is a string, not a function.

set validates a write

Write set percent(n: number) with one parameter. Assignment t.percent = 40 calls it. Throw when the value is illegal so a bad write never lands in the private field.

Example

class Gauge {
  private value = 0;

  get percent(): number {
    return this.value;
  }

  set percent(n: number) {
    if (n < 0 || n > 100) {
      throw new Error("percent out of range");
    }
    this.value = n;
  }
}

const g = new Gauge();
g.percent = 40;
console.log(g.percent);
try {
  g.percent = 140;
} catch (e) {
  if (e instanceof Error) {
    console.log(e.message);
  }
}
console.log(g.percent);

Output is 40, then percent out of range, then 40 again. The failed set did not overwrite the stored value.

Compute instead of storing

A getter does not have to return a field. It can derive a value. This class stores width and height and reports area as if it were a field.

Example

class Rect {
  constructor(
    private width: number,
    private height: number,
  ) {}

  get area(): number {
    return this.width * this.height;
  }
}

const card = new Rect(8, 5);
console.log(card.area);

Output is 40. There is no set area, so card.area = 10 does not compile. Read-only computed properties are a common pattern: expose the number, hide the formula.

Rules that keep this small

PieceDetail
get name()No parameter. Read with obj.name.
set name(v)One parameter. Write with obj.name = v.
private fieldThe actual storage. Callers never touch it.
throw in setReject values the object cannot hold.

You can write a getter without a setter (read-only). A setter without a getter is legal but unusual. Do not name a method getName and also a getter name for the same idea; pick one style. This tutorial uses get / set when the call site should look like a field.

Validate at the boundary

Keep fields private. Let getters report a safe view. Let setters enforce the rules. Next: type assertions, when you have information the checker cannot see and you tell it as T.

FAQ: TypeScript Getters and Setters

Common questions about this page.

What is the StudyGrid TypeScript tutorial?

The StudyGrid TypeScript tutorial follows the same chapter rhythm as C++: syntax, types, input, loops, functions, classes, generics, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run typescript getters setters examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn typescript getters setters in this TypeScript TypeScript lesson (TypeScript Getters and Setters).

Is the TypeScript editor the same as Try Python or Try C++?

No. Try TypeScript type-checks with tsc at /typescript/try and shows stdout plus compiler messages. Try Python stays at /try. Try C++ stays at /cpp/try. TypeScript lessons never open those editors.

Do I need to install a compiler to learn TypeScript?

No. Open a chapter, click Try it in TypeScript, and compile in the browser. You can also download a .ts file and compile locally with tsc.

Where should I start the TypeScript tutorial?

Start at TypeScript Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open TypeScript Examples, then generics, Map, and arrow functions. Use Next at the bottom of each chapter.

Is the TypeScript tutorial free?

Yes. The TypeScript workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.