1. 类的声明:
class Person {
firstName: string;
lastName: string;
age: number;
constructor(firstName: string, lastName: string, age: number) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
}
let person: Person = new Person("John", "Doe", 30);
2. 类的属性和方法:
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound(): void {
console.log("Some generic sound");
}
}
let dog: Animal = new Animal("Buddy");
dog.makeSound(); // 输出: Some generic sound
3. 继承:
class Dog extends Animal {
breed: string;
constructor(name: string, breed: string) {
super(name);
this.breed = breed;
}
makeSound(): void {
console.log("Woof!");
}
}
let myDog: Dog = new Dog("Buddy", "Labrador");
myDog.makeSound(); // 输出: Woof!
4. 访问修饰符:
- public: 默认的修饰符,属性和方法都可以在类的内外访问。
- private: 属性和方法只能在类的内部访问。
- protected: 属性和方法可以在类的内部和继承的子类中访问。
class Car {
private model: string;
constructor(model: string) {
this.model = model;
}
getModel(): string {
return this.model;
}
}
let myCar: Car = new Car("Toyota");
// console.log(myCar.model); // 错误,不能访问私有属性
console.log(myCar.getModel()); // 输出: Toyota
5. Getters 和 Setters:
class Circle {
private _radius: number;
constructor(radius: number) {
this._radius = radius;
}
get radius(): number {
return this._radius;
}
set radius(value: number) {
if (value >= 0) {
this._radius = value;
} else {
console.error("Radius cannot be negative.");
}
}
}
let myCircle: Circle = new Circle(5);
console.log(myCircle.radius); // 输出: 5
myCircle.radius = 10;
console.log(myCircle.radius); // 输出: 10
myCircle.radius = -1; // 输出错误信息: Radius cannot be negative.
6. 静态方法:
class MathUtil {
static add(x: number, y: number): number {
return x + y;
}
}
let result: number = MathUtil.add(3, 5);
console.log(result); // 输出: 8
这些是 TypeScript 中关于类的一些基本用法。类是面向对象编程中的核心概念,通过类,可以创建具有属性和方法的对象,实现代码的封装和复用。
转载请注明出处:http://www.zyzy.cn/article/detail/13022/TypeScript