Lesson 16 / 26
Classes in TypeScript
Typed properties, constructors, and interfaces a class must satisfy.
A typed class
Declare each property's type, then assign values in the constructor.
class Dog {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
bark(): string {
return `${this.name} says Woof!`;
}
}
const rex = new Dog("Rex", 3);Implementing an interface
implements makes TS check that the class actually provides everything the interface promises.
interface Speaker {
speak(): string;
}
class Cat implements Speaker {
speak(): string {
return "Meow!";
}
}
// If speak() were missing:
// Error: Class 'Cat' incorrectly implements interface 'Speaker'.Classes are structural too
A class doesn't need implements to satisfy an interface — if its shape matches, TS accepts it anywhere that interface is expected.