//接口是对象的状态(属性)和行为(方法)的抽象(描述)
//接口:是一种类型,是一种规范,是一种规则,是一种能力,是一种约束
// 需求: 创建人的对象, 需要对人的属性进行一定的约束
// id是number类型, 必须有, 只读的
// name是string类型, 必须有
// age是number类型, 必须有
// sex是string类型, 可以没有
interface Iperson{
// readonly id是只读的,是number类型。const修饰属性,想要设置该属性为只读的是不行的。
readonly id:number//只读,不可重新赋值。
name:String
age:number
sex?:string //?代表可有可无
}
const person:Iperson={
id:1,
name:'wy',
age:18,
//sex:'女'
}
person.sex="女";
console.log(person);
//函数类型
// 为了使用接口表示函数类型,我们需要给接口定义一个调用签名。
// 它就像是一个只有参数列表和返回值类型的函数定义。参数列表里的每个参数都需要名字和类型。
//定义一个接口,用来作为某个函数的类型来使用
interface ISearchFunc{
//定义一个调用签名
(source:string,subString:string):boolean
}
const searchString:ISearchFunc=function(source:string,subString:string){
// 在source字符串中查早subString这个字符串
return source.search(subString)>-1
}
// 调用函数
console.log(searchString('wy','y'));//true
/*
类类型: 实现接口
1. 一个类可以实现多个接口
2. 一个接口可以继承多个接口
*/
//定义一个接口
interface IFly{
fly()
}
interface Iswim{
swim()
}
//定义一个类,这个类的类型就是上面定义的接口(实际上也可以理解为IFly接口约束了当前的这个Person类)
class Person implements IFly,Iswim{//这个类的类型就是Ifly和ISwim(当前这个类可以实现多个接口,一个同时也可以被多多个接口进行约束)
fly(){
console.log("我会飞了,我是超人")
}
swim(){
console.log("我会游泳了,我好棒")
}
}
const person1=new Person();
person1.fly();
person1.swim();
//定义一个接口,进程其他的多个接口
interface IMyFlyAndSwim extends Iswim,IFly{}
//定义一个类直接实现IMyFlyAndSwim这个接口
class Person2 implements IMyFlyAndSwim{
fly(){
console.log("我会飞了,我是超人2")
}
swim(){
console.log("我会游泳了,我好棒2")
}
}
const person3=new Person2();
person3.fly();
person3.swim();
//总结:接口和接口之间叫继承(使用的是extends),类与接口之间叫实现(使用的是implements)