Classes in TypeScript vs JavaScript

Zoe Friedman
3 min readSep 15, 2021

and an intro to public, private, and protected modifiers

Classes in TypeScript

At their most rudimentary, classes in TypeScript are very similar to ES2015 JavaScript classes. Here is a very basic class outlined in TypeScript:

class Monster {
growl(): void {
console.log('Grrrr')
}
scare(): string {
return "Placeholder for the scariest thing imaginable."
}
}

The only visible difference here is we have to specify what type our function’s return value will be. That syntax involves a semi-colon, followed by the type, as you can see above. The first function returns nothing, so its return value type will be “void”. The second function will return a string.

With its full syntax, here is how we can define properties in our classes. Observe two ways. First, hard coded—

class Monster {

color: string = "brown"
...}

Second, dynamically with a constructor:

class Monster {

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

If you are initializing the variable in the constructor, you must first define it above with the type.

However, you can see with the constructor, this gets a little repetitive. Therefore, we can use the “public” modifier to shorten the syntax:

class Monster {  constructor(public color: string){}  ...}let sully = new Monster("blue and green")
console.log(sully.color) // blue and green

If you add the public modifier, whatever you pass in (in order) will be assigned as an instance variable to that instance of the class!

More on modifiers

“Public,” “private,” and “protected” modifiers are helpful throughout our classes in TypeScript, especially when used with methods. By default, all methods are public.

Private methods can only be called by other methods inside of the class. This is handy if you have a complicated, special way of using a method that could cause major issues if use inadvertently. This below will work:

class Monster {
private roar(): string{
return "ROOOOOOAAARRR"
}
scare(): string{
return this.roar()
}
}
let gizmo = new Monster("brown and white")
gizmo.roar()

However, look what happens when I try to call roar outside of my Monster class:

TypeScript throws me an error, and when I hover over I see a very helpful explanation.

Similarly, “protected” methods are like “private” methods but they can be accessed in children. So if I had a “Mogwai” class that extended my “Monster” class. I could potentially make the roar method “protected” so that the Mogwai’s could use it as well.

class Monster {
protected roar(): string{
return "ROOOOOOAAARRR"
}
}
class Mogwai extends Monster {
scare(): string{
return this.roar()
}
}

These modifiers work with our variables as well! Our variables can also be modified to be “private” or “protected.”

--

--