类
Tutorial: TS初级一
Category: TS
Published: 2026-04-07 13:58:26
Views: 20
Likes: 0
Comments: 0
类的使用
- 实例一
class Person1 {
age: number;
gender: string;
constructor(age: number, gender: string) {
this.age = age;
this.gender = gender;
}
}
const p1 = new Person1(19, "女");
console.log(p1.age, p1.gender);
class Point {
x = 2;
y = 3;
scale(n: number) {
this.x *= n;
this.y *= n;
}
}
const p2 = new Point();
p2.scale(10);
console.log(p2.x, p2.y);
class Animal {
move() {
console.log("Animal move");
}
}
class Dog extends Animal {
bark() {
console.log("Dog wang");
}
}
const d = new Dog();
d.move();
d.bark();
interface Singable {
sing(song: string): void;
}
class SingPerson implements Singable {
sing(song: string) {
console.log(song);
}
}
const p = new SingPerson();
p.sing("你是我的小苹果");
- 实例二
class Animal {
name: string;
static categoies: string[] = ["mammal", "bird"];
static isAnimal(a) {
return a instanceof Animal;
}
constructor(name: string) {
this.name = name;
}
run() {
return `${this.name} is running`;
}
}
console.log(Animal.categoies);
const snake = new Animal("lily");
console.log(Animal.isAnimal(snake));
class Dog extends Animal {
bark() {
return `${this.name} is barking`;
}
}
const xiaobao = new Dog("xiaobao");
class Cat extends Animal {
constructor(name) {
super(name);
console.log(this.name);
}
run() {
return "Meow, " + super.run();
}
}
const maomao = new Cat("maomao");
interface Radio {
switchRadio(): void;
}
interface Battery {
checkBatteryStatus();
}
interface RadioWithBattery extends Radio {
checkBatteryStatus();
}
class Car implements Radio {
switchRadio() {}
}
class Cellphone implements RadioWithBattery {
switchRadio() {}
checkBatteryStatus() {}
}
- 类兼容性
class Point {
x: number;
y: number;
}
class Point2D {
x: number;
y: number;
}
const p: Point = new Point2D();
class Point3D {
x: number;
y: number;
z: number;
}
const p1: Point = new Point3D();
- 接口兼容性
interface Point {
x: number;
y: number;
}
interface Point2D {
x: number;
y: number;
}
interface Point3D {
x: number;
y: number;
z: number;
}
let p1: Point;
let p2: Point2D;
let p3: Point3D;
class Point4D {
x: number;
y: number;
z: number;
}
p2 = new Point4D();