Classes¶
This lesson covers classes, access modifiers, readonly, implements, and the differences between classes and interfaces.
Class basics¶
class Lesson {
id: string
title: string
constructor(id: string, title: string) {
this.id = id
this.title = title
}
summary(): string {
return `${this.id}: ${this.title}`
}
}
Create an instance with new.
Parameter properties¶
TypeScript can declare and assign properties directly in the constructor.
class Course {
constructor(
public readonly id: string,
public title: string,
private lessons: string[] = []
) {}
addLesson(lesson: string): void {
this.lessons.push(lesson)
}
}
Access modifiers¶
| Modifier | Access |
|---|---|
public |
Anywhere |
private |
Only inside the class |
protected |
Inside the class and subclasses |
implements¶
A class can implement an interface.
interface Printable {
print(): string
}
class Report implements Printable {
constructor(public content: string) {}
print(): string {
return this.content
}
}
readonly¶
A readonly property can be assigned once during initialization.
Inheritance¶
class Animal {
constructor(public name: string) {}
speak(): string {
return `${this.name} makes a sound`
}
}
class Dog extends Animal {
speak(): string {
return `${this.name} barks`
}
}
Classes versus interfaces¶
- Use
classwhen you need runtime behavior, constructors, or instances. - Use
interfacewhen you only need to describe a shape.
Hands-on: library catalog¶
- Create
src/library.ts. - Define
interface Borrowable { borrow(): void; returnItem(): void }. - Create an abstract-ish base class
CatalogItemwithid,title, and adescription()method. - Create
class Book extends CatalogItem implements Borrowablewithauthor,isBorrowed, and methodsborrow/returnItem. - Create
class DVD extends CatalogItem implements BorrowablewithruntimeMinutes. - Create an array of
CatalogItem[], add aBookand aDVD, and calldescription()on each. - Try to access a
privateproperty from outside the class and observe the error.