类和接口
- 类的定义
ts
// 方式一
class Animal {
name: string // 指的是this.name的类型,默认是public修饰符,子类和实例都能访问
private age: number // private只有自己能用
protected sex: string // protected子类也可以使用
constructor(name: string) {
this.name = name
}
run() {}
}
// 方式二
// 接口实现类和继承类的区别在于,接口实现类可以让两个有相同属性的不同类,复用代码
interface ClockInterface {
currentTime: number
alert(): void
}
interface GameInterface {
play(): void
}
interface ClockStatic {
new (h: number, m: number): void // new用来声明它是构造函数
}
// implement可以实现多个接口
// implement实现的interface约束的是类的实例的类型,而非类的静态类型(即我们定义的Clock)
const Clock:ClockStatic = class clock implement ClockInterface,GameInterface {
static time = 12
// 此处的构造函数受ClockStatic接口约束
constructor(h: number, m: number) {}
currentTime: number = 123
alert() {
}
play() {}
}
- 接口继承类
- 接口继承的是类的成员类型
- 接口继承的private和protected成员只能被这个类或它子类实现
- 类的继承
ts
class Dog extends Animal {
bark() {
// 直接使用父类属性
return `${this.name} is barking`
}
}
- 类的多态
ts
class Cat extends Animal {
constructor(name) {
super(name)
}
// 重写方法
run() {
return 'cat'
}
}
- 类成员简写
ts
interface IFood {
type: string
}
class Food implements IFood {
constructor(public type: string) {}
// 相当于
// public type
//constructor(type: string) {
// this.type = type
//}
}