O'Reilly logo

Mastering TypeScript by Nathan Rozentals

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Class modifiers

As we discussed briefly in the opening chapter, TypeScript introduces the public and private access modifiers to mark variables and functions as either public or private. Traditionally, JavaScript programmers have used a simple naming convention of prefixing variables with an underscore (_) to indicate that they are private variables. This naming convention, however, does not stop anyone from actually modifying such variables inadvertently.

Let's take a look at a TypeScript code sample to illustrate this point:

class ClassWithModifiers { private _id: number; private _name: string; constructor(id: number, name: string) { this._id = id; this._name = name; } modifyId(id: number) { this._id = id; this.updateNameFromId(); } private updateNameFromId() ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required