class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
let greeter = new Greeter("world");
console.log(greeter.greet());
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
move(distance: number = 0) {
console.log(`${this.name} moved ${distance}m.`);
}
}
class Dog extends Animal {
bark() {
console.log("Woof! Woof!");
}
}
const dog = new Dog("Buddy");
dog.bark();
dog.move(10);
TypeScript支持三种访问修饰符:
public - 公开的,默认修饰符private - 私有的,只能在类内部访问protected - 受保护的,可以在类及其子类中访问class Person {
public name: string;
private age: number;
protected email: string;
constructor(name: string, age: number, email: string) {
this.name = name;
this.age = age;
this.email = email;
}
public getAge(): number {
return this.age;
}
}
class Employee extends Person {
private department: string;
constructor(name: string, age: number, email: string, dept: string) {
super(name, age, email);
this.department = dept;
}
public getEmail(): string {
return this.email; // 可以访问protected属性
}
}
let person = new Person("Alice", 25, "alice@example.com");
console.log(person.name); // 正确
console.log(person.age); // 错误:age是私有的
class Octopus {
readonly name: string;
readonly numberOfLegs: number = 8;
constructor(name: string) {
this.name = name;
}
}
let dad = new Octopus("Man with the 8 strong legs");
dad.name = "Man with the 3-piece suit"; // 错误!name是只读的
在构造函数参数中使用修饰符可以自动创建和初始化成员:
class Person {
constructor(
public name: string,
private age: number,
protected email: string
) {}
}
// 等价于
class Person {
public name: string;
private age: number;
protected email: string;
constructor(name: string, age: number, email: string) {
this.name = name;
this.age = age;
this.email = email;
}
}
class Employee {
private _fullName: string = "";
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (newName && newName.length > 0) {
this._fullName = newName;
} else {
throw new Error("Name cannot be empty");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
console.log(employee.fullName);
class Grid {
static origin = { x: 0, y: 0 };
static calculateDistance(point: { x: number; y: number }) {
let xDist = point.x - Grid.origin.x;
let yDist = point.y - Grid.origin.y;
return Math.sqrt(xDist * xDist + yDist * yDist);
}
}
console.log(Grid.origin);
console.log(Grid.calculateDistance({ x: 10, y: 10 }));
abstract class Animal {
abstract makeSound(): void;
move(): void {
console.log("Moving...");
}
}
class Dog extends Animal {
makeSound() {
console.log("Woof! Woof!");
}
}
let dog = new Dog();
dog.makeSound();
dog.move();
let animal = new Animal(); // 错误:不能创建抽象类的实例
类定义会创建两个东西:类的实例类型和构造函数。因此类也可以当作接口使用。