In the JavaScript track you already built classes: blueprints for objects, with a constructor that stores data on this and methods that read it. TypeScript adds two things: a type for every property, and access modifiers that decide where a property may be used from. Picture an office: the lobby is open to anyone, the archive door has a "Staff only" sign on it, and the safe is properly locked. A sign on a door only works while there's a guard to tell people off, and the guard is TypeScript, checking your code.
Typed properties and access modifiers
class Animal {
public name: string
private sound: string
constructor(name: string, sound: string) {
this.name = name
this.sound = sound
}
speak(): string {
return this.name + " says: " + this.sound
}
}
public name: stringandprivate sound: stringdeclare the properties at the top of the class, with their types. In TypeScript a property has to be declared first:this.name = namewithout a declaration is the errorProperty 'name' does not exist on type 'Animal'.ts(2339).- There are three access modifiers:
public(usable from anywhere, and the default when you write nothing),private(only inside this class), andprotected(inside this class and its subclasses). There's one more modifier,readonly: readable from anywhere, but it can only be set in its declaration or in theconstructor. speak(): stringmeans the method returns astring:new Animal("Cat", "Meow").speak()gives"Cat says: Meow".
Who may touch what
Now add a subclass Cat, then code outside the class that reads and changes sound:
class Cat extends Animal {
showOff(): string {
return "My sound is " + this.sound
}
}
const cat = new Cat("Cat", "Meow")
console.log(cat.speak())
console.log(cat.showOff())
console.log(cat.sound)
cat.sound = "Woof"
console.log(cat.speak())
Change the modifier in front of sound, and TypeScript judges every line that touches it:
Line touching sound |
public |
private |
protected |
readonly |
|---|---|---|---|---|
inside Animal, method speak |
allowed | allowed | allowed | allowed |
in the subclass Cat, method showOff |
allowed | ts(2341) | allowed | allowed |
outside, reading cat.sound |
allowed | ts(2341) | ts(2445) | allowed |
outside, changing cat.sound = "Woof" |
allowed | ts(2341) | ts(2445) | ts(2540) |
- ts(2341):
Property 'sound' is private and only accessible within class 'Animal'.Not even a subclass may. - ts(2445):
Property 'sound' is protected and only accessible within class 'Animal' and its subclasses. - ts(2540):
Cannot assign to 'sound' because it is a read-only property.
Parameter properties: declare and fill in one go
Writing sound three times (declaration, parameter, this.sound = sound) gets tiring. The shortcut: put the access modifier straight on the constructor parameter.
class Animal {
constructor(public name: string, private sound: string) {}
speak(): string {
return this.name + " says: " + this.sound
}
}
public name: stringinside theconstructorparentheses declares the propertynameand fills it with the first argument at the same time, so theconstructorbody can stay empty,{}. This is called a parameter property, and this class is exactly the same as the long version above.- The modifier is required:
public,private,protected, orreadonly. A parameter without one stays a plain parameter and does not become a property.
Since TypeScript 5.8 there's an erasableSyntaxOnly option, for projects that run .ts just by deleting the types (for example Node.js running a .ts file directly). A parameter property needs extra code in the JavaScript (this.name = name), so with that option on it is rejected: This syntax is not allowed when 'erasableSyntaxOnly' is enabled. ts(1294). In such a project, use the long version. The React, Vue and Vanilla TypeScript templates of npm create vite@latest also turn this option on, so the long version is the one to use in a new Vite project too.
private only exists while checking
Types and access modifiers are only used while TypeScript checks your code. When tsc turns it into JavaScript, they are all deleted. The long version and the parameter property both become the same JS:
class Animal {
name;
sound;
constructor(name, sound) {
this.name = name;
this.sound = sound;
}
// speak() is still there, without ": string"
}
The word private is gone, and sound is an ordinary property. So the Cat program above, if its JS is run despite the errors, prints Cat says: Meow, My sound is Meow, Meow, then Cat says: Woof. cat.sound prints Meow, and changing it to Woof works too. private is a "Staff only" sign: TypeScript tells you off in the editor, but the JavaScript locks nothing.
Need a real lock? Use JavaScript's own private field, which starts with #:
class Animal {
#sound: string
constructor(public name: string, sound: string) {
this.#sound = sound
}
}
#soundis still there in the compiled JavaScript, and JavaScript itself guards it.- From outside the class (a subclass too), TypeScript rejects
cat.#sound:Property '#sound' is not accessible outside class 'Animal' because it has a private identifier.ts(18013). If the JS is run anyway, the file doesn't run at all:SyntaxError: Private field '#sound' must be declared in an enclosing class. #can't be used on a parameter property, so declare it at the top and fill it in theconstructor.
implements and abstract classes
implements is a promise that the class matches the shape of an interface (from the Interface lesson). If class Robot implements CanSpeak forgets the method speak() its interface asks for, TypeScript rejects it: Class 'Robot' incorrectly implements interface 'CanSpeak'. ts(2420).
An abstract class is a class that may only be a parent. It can have abstract methods: methods with no body that every subclass must write.
abstract class Animal {
constructor(public name: string) {}
abstract speak(): string
}
class Cat extends Animal {
speak(): string { return "Meow" }
}
new Cat("Cat").speak() // "Meow"
new Animal("Who") // error ts(2511)
new Animal(...)is rejected:Cannot create an instance of an abstract class.ts(2511).- A subclass that forgets to write
speak, sayclass Fish extends Animal {}, is rejected too:Non-abstract class 'Fish' does not implement inherited abstract member speak from class 'Animal'.ts(2515). - Like
private, the wordsabstractandimplementsare deleted from the JavaScript. Only TypeScript guards them.
⚠️ Why is sound undefined, or refused?
- A parameter without a modifier.
constructor(public name: string, sound: string) {}only makes the propertyname.this.soundbecomes the errorProperty 'sound' does not exist on type 'Animal'.ts(2339), and in JavaScript its value isundefined: the sentence comes out asCat says: undefined. - A declaration with nothing put in it.
private sound: stringis written at the top, butthis.sound = soundis forgotten:Property 'sound' has no initializer and is not definitely assigned in the constructor.ts(2564). - Reading
soundfrom outside the class in the exercise. The exercise runs the TypeScript checker first (instrictmode, liketsc --noEmit), soconsole.log(cat.sound)outside the class fails straight away witherror TS2341. The sentence must also be exactlyCat says: Meow, spaces and colon included.
TL;DR: In a TypeScript class, properties are declared with their types. public is usable from anywhere (the default), private only inside that class, protected inside that class and its subclasses, and readonly can be read but only set in its declaration or the constructor. A parameter property, constructor(public name: string, private sound: string) {}, declares and fills in one go, as long as it has a modifier (and it's rejected when erasableSyntaxOnly is on). All these modifiers are only checked by TypeScript and vanish in JavaScript; the lock that's still there when the program runs is #field. implements promises an interface's shape, and an abstract class can't be newed and forces subclasses to write its abstract methods.
⚡ Typed properties and access modifiers
Write:
class Animal {
public name: string
private sound: string
constructor(name: string, sound: string) {
this.name = name
this.sound = sound
}
}
Meaning: In TypeScript, properties are declared first, with their types. public can be used from anywhere, private only inside this class, not even in a subclass. protected works in this class and its subclasses.
⚡ Declare and fill in one go
Write:
class Animal {
constructor(public name: string, private sound: string) {}
speak(): string {
return this.name + " says: " + this.sound
}
}
Meaning: An access modifier on a constructor parameter declares the property and fills it in one go, so the body can stay empty. The modifier is required: a parameter without one doesn't become a property, and you get Cat says: undefined.
In the exercise, the sentence has to be exactly Cat says: Meow, spaces and colon included.
⚡ private only exists while checking
Guess first: if the JavaScript runs anyway despite the error, what does cat.sound from outside the class print?
Meow. The word private is removed when it becomes JavaScript, so sound is just an ordinary property.
Meaning: private is a "Staff only" sign: TypeScript warns you in the editor, but the JavaScript locks nothing. Need a real lock? Use JavaScript's own private field, #sound, which stays guarded while the program runs.