TypeScript的核心原则之一是对值所具有的结构进行类型检查,我们使用接口(Interfaces)来定义对象的类型。接口是对象的状态(属性)和行为(方法)的抽象(描述)
接口定义
// 定义人的接口
interface IPerson {
readonly id: number, //只读属性
name: string,
age: number,
sex?: string, //可选属性
}
const person: IPerson = {
id: 1,
name: "栗子",
age: 18,
}
函数类型
使用接口表示函数类型,需要给接口定义一个调用签名,它就像是一个只有参数列表和返回值类型的函数定义,参数列表里的每个参数都需要名字和类型。
// 定义一个接口,用来作为某个函数的类型使用
interface SearchFunc {
(source: string, subString: string): boolean
}
// 定义一个函数,该类型就是上面定义的接口
const mySearch: SearchFunc = function (source: string, sub: string): boolean {
// 在source字符串中查找sub这个字符串
return source.search(sub) > -1
}
类类型
接口和接口之间叫继承(使用的是extends关键字),类和接口之间叫实现(使用的是implements)
interface IFly {
// 该方法没有任何的实现(方法中什么都没有)
fly(): any
}
interface ISwim {
// 该方法没有任何的实现(方法中什么都没有)
swim(): any
}
// 定义一个类,这个类的类型就是上面定义的接口(IFly接口约束了当前的这个Person类)
class Person implements IFly {
// 实现接口中的方法
fly() {
console.log("我要飞");
}
}
// 实例化对象
const person = new Person()
// 调用方法
person.fly()
// 定义一个类,这个类的类型就是IFly和ISwim(当前这个类可以实现多个接口)
class Person2 implements IFly, ISwim {
// 实现接口中的方法
fly() {
console.log("我要飞");
},
swim() {
console.log("我要游");
}
}
// 实例化对象
const person2 = new Person2()
// 调用方法
person2.fly()
person2.swim()
// 定义了一个接口,继承其他的多个接口
interface IMyFlyAndSwim extends IFly, ISwim { }
// 定义一个类,直接实现IMyFlyAndSwim这个接口
class Person3 implements IMyFlyAndSwim {
// 实现接口中的方法
fly() {
console.log("我要飞");
},
swim() {
console.log("我要游");
}
}
// 实例化对象
const person3 = new Person3()
// 调用方法
person3.fly()
person3.swim()