介绍
TypeScript 的核心原则之一是对值所具有的结构进行类型检查。我们使用接口(Interfaces)来定义对象的类型。
基本语法
(() => {
// 定义一个接口 给接口作为Iperson对象的类型使用
interface Iperson {
readonly id:number //readonly 只读属性
name?: string // ? 可选属性
age:number
}
// 定义一个接口类型的对象
const person: Iperson = {
id:1,
// name: "小明",
age:18
}
})()
函数类型
(() => {
// 为了使用接口表示函数类型,我们需要给接口定义一个调用签名
// 他就像是一个只有参数列表和返回值类型的函数定义。参数列表里的每个参数都需要名字和类型。
// 定义一个接口作为某一个函数的类型来使用
interface IsearchFun {
// 定义一个调用签名
(source: string, subString: string): boolean
}
// 定义一个函数 该类型就是上面定义的接口
const searchString:IsearchFun = function (source: string, subString: string): boolean {
return source.search(subString) > -1
}
console.log(searchString('231','2')) // true
})()
接口中的类 的类型
接口类的简单使用
(() => {
// 类的类型 可以通过接口来实现
// 定义一个接口
interface Ifly {
// 定义一个方法
fly()
}
interface Iswim {
// 定义一个方法
swim()
}
// 定义一个类 这个类的类型 为接口类型 (在类中实现接口的约束)
// Person 类实现了 Ifly,Iswim 接口
class Person implements Ifly,Iswim {
fly() {
console.log('fly方法')
}
swim() {
console.log('swim方法')
}
}
const person = new Person
person.fly()
person.swim()
})()
接口的继承
(() => {
// 类的类型 可以通过接口来实现
// 定义一个接口
interface Ifly {
// 定义一个方法
fly()
}
interface Iswim {
// 定义一个方法
swim()
}
// 定义一个类 这个类的类型 为接口类型
// Person 类实现了 Ifly,Iswim 接口
class Person implements Ifly,Iswim {
fly() {
console.log('fly方法')
}
swim() {
console.log('swim方法')
}
}
const person = new Person
person.fly()
person.swim()
// 接口的继承
// 定义一个接口 继承之前的接口
interface animation extends Ifly,Iswim {}
class Person1 implements animation {
fly() {
console.log('fly方法1')
}
swim() {
console.log('swim方法1')
}
}
const person1 = new Person1()
person1.fly()
person1.swim()
})()
个人理解
implements和extends的区别(c++等支持多继承请绕路)
继承 通过类 可以继承父类的内容 一个子类只能通过一个父类继承
实现 通过接口 可以约束子类的内容 一个子类可以通过多个接口实现
接口可以继承自其他多个接口(类似合并)