Lesson 12 of 15
Classes
Classes
TypeScript classes are JavaScript classes with type annotations. Declare property types in the class body:
class Animal {
name: string;
sound: string;
constructor(name: string, sound: string) {
this.name = name;
this.sound = sound;
}
speak(): string {
return this.name + " says " + this.sound;
}
}
const dog = new Animal("Dog", "woof");
console.log(dog.speak()); // Dog says woof
Access Modifiers
TypeScript adds access modifiers:
public— accessible anywhere (default)private— accessible only within the classreadonly— can only be assigned once (in the constructor)
class Counter {
private count: number = 0;
increment(): void {
this.count++;
}
value(): number {
return this.count;
}
}
Constructor Shorthand
TypeScript lets you declare and assign in one step:
class Point {
constructor(public x: number, public y: number) {}
toString(): string {
return "(" + this.x + ", " + this.y + ")";
}
}
Your Task
Write a class Circle with a radius: number property, a constructor, an area() method returning Math.PI * r * r rounded to 2 decimal places, and a perimeter() method returning 2 * Math.PI * r rounded to 2 decimal places.
TypeScript loading...
Loading...
Click "Run" to execute your code.