一、interface
// 多用来约束对象
interface Girl {
name: string;
age: number;
school?: string;
[propname:string]:any;
say():string;
}
// 接口不仅可以限制对象,还可以限制类
class Xiaohong implements Girl {
}
// 接口的继承
interface Teacher extends Girl {
teach(): string
}
二、类
1、super关键字
可以调用父类中的方法,在子类的构造函数中一定要调用
class Student extends Person {
constructor() {
super()
}
}
2、private、public(默认值)
private只允许在类的内部使用,public在类的外部也可以使用
private使用场景如下:
class Person {
// 类的内部,大括号之间的
constructor(private _age:number){}
get age() { return this._age }
set age(age: number) {
this._age -= 10
}
}
3、static,使用类直接调用方法
4、抽象类
abstract class Girl {
// 抽象类中的方法为抽象方法
abstract skill()
}
class Teacher extends Girl {
// 继承了抽象类,就要实现它的抽象方法
skill(){
console.log('教书')
}
}
三、联合类型和类型保护
interface Teacher {
age: 22;
teach():void
}
interface Student {
age: 15;
study():void
}
function judge (people: Teacher | Student) {
// Teacher | Student这种为联合类型
if(people.age > 20){
// a、断言的方式
(people as Teacher).teach()
}
if('teach' in people) {
// b、in的方式
people.teach()
}
// c、typeof的方式
// d、instanceof的方式
}
四、枚举类型
enum Option {
JUMP = 'JUMP', //默认值为0
DIALOG = 'DIALOG'
}
五、泛型
1、在函数中使用泛型,尖括号都是写在函数名后面的
泛型数组的表示如下
function fn<T>(params: T[]) {}
function fn<T>(params: Array<T>) {}
fn<string>(['aa', 'bb']) //
2、在类中使用泛型,尖括号写在类名后面
class SelectDog<T> {
constructor(dogs: T[]){}
getDog(index: number){
return this.dogs[index]
}
}
const selectDog = new SelectDog<string>(['小黑', '小白'])
3、泛型的约束,使用extends
interface Dog {
name: string,
eat(): void
}
function fn<T extends string | number>(params: T[]) {}
function fn<T extends Dog>(params: T[]) {}