interface接口
接口是对象的状态(属性)和行为(方法)的抽象(描述)
// 需求: 创建人的对象, 需要对人的属性进行一定的约束 // id是number类型, 必须有, 只读的 // name是string类型, 必须有 // age是number类型, 必须有 // sex是string类型, 可以没有 // 定义接口 对于某个对象属性的一种规范 interface Iperson { // readonly 代表当前对象的属性只可读,不可写 readonly id:number, name:string, age:number, // ? 代表当前对象的属性可有可无 sex?:string } // 定义对象 const person:Iperson = { id:1, name:'小米', age:18, } console.log(person) person.sex = '男' // person.id = 100 console.log(person)
函数类型
// 定义一个接口,用来作为某个函数的类型使用 interface func { (str1:string,str2:string):boolean } // 定义一个函数,函数的类型就是上面定义的接口 // 箭头函数 const searchFn:func = (str1:string,str2:string):boolean =>{ return str1.search(str2) != -1 } // 普通函数 // const searchFn:func = function (str1:string,str2:string):boolean{ // return str1.search(str2) != -1 // } console.log(searchFn('我是帅哥','帅'))
类类型
// 类的类型:类的类型可以通过接口来实现 // 定义第一个接口 interface IFly{ // fly方法没有任何实现 fly() } // 定义一个类,这个类的类型就是上面定义的接口 class Person implements IFly { fly() { console.log('我会飞') } } // 实例化 const person = new Person() person.fly() // 定义第二个接口 interface ISwim{ swim() } // 一个类同时被两个接口来约束 class Person2 implements IFly,ISwim { fly() { console.log('我会飞1') } swim() { console.log('我会游泳1') } } const person2 = new Person2() person2.fly() person2.swim() // 定义一个接口来继承其他接口 interface myFlyAndSwim extends IFly,ISwim {} class Person3 implements myFlyAndSwim{ fly() { console.log('我会飞222') } swim() { console.log('我会游泳222'); } } const person3 = new Person3() person3.fly() person3.swim()
还没有评论,来说两句吧...