抽象类

抽象(abstract)类是专门用于被继承的类,永远不可实例化,用于设定子类规范
抽象方法必须定义在抽象类中,且不能包含方法体,抽象类的子类必须包含所有的抽象方法定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
abstract class Animal {
constructor(
public length: number, //ts中定义类属性的简写形式
public weight: number,
) {} //抽象方法也要有构造函数,虽然永远不能实例化
abstract breathe(): void
abstract eat(): void
showInfo(): void {
console.log(`身长${this.length},体重${this.weight}`)
} //非抽象方法可在抽象类里直接实现
}

class Cat extends Animal {
constructor(
public length: number,
public weight: number,
) {
super(length, weight) //super()函数规定从父类中继承的属性
}

breathe() {
console.log("猫在呼吸")
}
eat() {
console.log("猫在吃小鱼干")
} //必须包含所有抽象方法的实现
}

class Dog extends Animal {
constructor(
public length: number,
public weight: number,
) {
super(length, weight)
}

breathe() {
console.log("狗在呼吸")
}
eat() {
console.log("狗在啃骨头")
} //必须包含所有抽象方法的实现
}

let kitty = new Cat(50, 20)
kitty.eat()
kitty.breathe()
kitty.showInfo()

let 旺财 = new Dog(100, 50)
旺财.eat()
旺财.breathe()
旺财.showInfo()

接口(interface)

接口是一种定义结构的方式,用于定义类、对象、函数的格式
接口支持通过索引签名灵活定义属性,支持使用’?’标记可选属性,支持使用readonly规定只读属性

接口描述函数:

1
2
3
4
5
6
7
8
interface SearchFunc {
(source: string, subString: string): boolean;
}

let mySearch: SearchFunc;
mySearch = function(src: string, sub: string): boolean {
return src.search(sub) !== -1;
};

oop综合应用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
interface AnimalInterface {
length: number
weight: number
eat(): void
sleep(): void
}

abstract class Mammal implements AnimalInterface {
constructor(
public length: number,
public weight: number,
) {}
abstract eat(): void
abstract sleep(): void
}

class Person extends Mammal implements AnimalInterface {
constructor(
public length: number,
public weight: number,
) {
super(length, weight)
}
eat() {
console.log("人在吃饭")
}
sleep() {
console.log("人在睡觉")
}
}

接口可直接作为对象的类型,用于规定对象的结构:

1
2
3
4
5
6
7
8
9
10
interface PersonInfo {
name: string
age: number
[key: string]: unknown
}
let 张三: PersonInfo = {
name: "张三",
age: 18,
gender: "男",
}

接口具有继承性,子接口可继承父接口的所有属性,同样用extends关键字实现

接口具有自动合并性,当重新定义一个已经存在的接口时,两个接口会自动合并,最终得到同时具有二者属性的新接口

泛型

定义函数、类、接口时,可使用类型参数表示未指定的类型,类型参数在使用时才被指定具体的类型。泛型让同一段代码适用于多种类型的数据,同时保持了类型的安全性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//泛型函数
function print<T>(a: T): T {
console.log(a)
return a
}
print<number>(123)
print('hello') //大多数情况下<>可省略
print(true)

//泛型接口
interface abcdInterface<T,Y,P,E>{ //可定义多个类型参数,用逗号分隔
a:T,
b:Y,
c:P,
d(x:E):E;
}

//泛型类
class efgClass<T> {
constructor(
public d: T,
public e: T,
) {}
g(x: T): T {
return x
}
}