定义一个接口,作为person对象的类型使用,从而限定该对象中的属性数据
需求: 创建人的对象, 需要对人的属性进行一定的约束
// 在 TypeScript 中,我们使用接口(Interfaces)来定义对象的类型
interface IPerson {
readonly id: number // 表示 id是只读的,是number类型
name: string // 默认是必须有的
age: number
sex?: string // ? 表示此属性可有可无
}
const person: IPerson = {
id: 1,
name: 'tom',
age: 20,
}
console.log(person)
// person.id = 100 // id属性,只读,无法修改,报错
person.sex = 'woman'
console.log(person)
// person.desc = "说明" // 不存在此属性,报错
定义一个接口,用来作为某个函数的类型使用,接口可以描述函数类型(参数的类型与返回的类型)
interface SearchFunc {
// 定义一个调用签名
(source: string, subString: string): boolean
}
// 定义一个函数,该类型就是上面定义的接口
const mySearch: SearchFunc = function (source: string, sub: string): boolean {
return source.search(sub) > -1
}
console.log(mySearch('abcd', 'bc'))
注意: 接口中的约束,必须在类中实现,而类中可以有其它任意数据
implements// 定义一个接口
interface IFly {
fly()
}
// 定义一个类,这个类的类型就是上面定义的接口(也就是,IFly接口约束了当前这个Person类)
class Person implements IFly { // implements 接口约束类
fly() {
console.log('飞了!')
}
}
const person = new Person()
person.fly()
implements多个接口之间用 , 相连即可
// 定义一个接口
interface ISwim {
swim()
}
interface IFly {
fly()
}
// 定义一个类,这个类的类型是IFly 和 ISwim (一个类同时可以被多个接口约束)
class Person2 implements IFly,ISwim {
fly() {
console.log('又飞了!')
}
swim() {
console.log('游走了!')
}
say(){
console.log('我说!')
}
}
const person2 = new Person2()
person2.fly()
person2.swim()
person2.say()
// 注意:接口中的约束,必须在类中实现,而类中可以有其它任意数据
// 接口1
interface ISwim {
swim()
}
// 接口2
interface IFly {
fly()
}
// 接口3 继承接口1和接口2
interface ISmFly extends IFly,ISwim { }
class Person3 implements ISmFly {
fly() {
console.log('又飞了3!')
}
swim() {
console.log('游走了3!')
}
}
const person3 = new Person3()
person3.fly()
person3.swim()
extends implements