前言
- 是对象的
状态(属性)
和 行为(方法)
的 抽象(描述)
- 是一种
规范
、规则
、能力
、约束
一、基本使用
- 对变量使用
interface
,同样也是 :interfaceName
- 变量需要
严格按照 interface 内部的限制
,多传、少传、错传都会报错 readonly
表示 只读
,修改则会报错?:
表示 可有可无
例:创建人的对象,姓名只读不可修改,性别可传可不传
interface IPerson {
readonly name: string;
age: number;
number: number
sex ?: string
}
const person:IPerson = {
name: 'blue',
age: 18,
number: 4103221996,
sex: '女',
}
person.age = 16
二、函数类型
- 通过
接口
的方式作为 函数的类型
来使用 - 白话:定义函数的
参数类型
和 返回值类型
例:定义一个函数,展示字符串 indexOf 的用法
interface ISearchFun {
(search: string, target: string) : boolean
}
const exitStr: ISearchFun = function (search: string, target: string) : boolean {
return search.indexOf(target) > 0
}
const exitStr2: ISearchFun = function (searchNew: string, targetNew: string) : boolean {
return searchNew.indexOf(targetNew) > 0
}
三、类 类型
3.1、基本使用
- 顾名思义,就是
类的类型
类
与 interface
的关系,叫做 实现
,需要通过 implements
关键字- 在类中同样
也需要严格按照 interface 中定义的限制
实现
例:类中定义一个方法fly,fly返回值是string
interface IFly {
fly():string
}
class Person implements IFly {
fly () {
console.log('我会飞了')
return '哈哈哈'
}
}
const person1 = new Person()
person1.fly()
3.2、一个类实现多个接口
- 同样的
implements
语法,接口之间 ,
隔开
interface IFly {
fly():string
}
interface ISwim {
swim():void
}
class Person2 implements IFly, ISwim {
fly () {
console.log('我会飞了')
return '哈哈哈'
}
swim () {
console.log('我会游泳了')
}
}
const person2 = new Person2()
person2.fly()
person2.swim()
3.3、先把接口合并,再让类去实现合并后的接口
- 多个接口之间的
继承
, 通过 extends
关键字
interface IFly {
fly():string
}
interface ISwim {
swim():void
}
interface IFlyAndISwim extends IFly, ISwim {}
class Person3 implements IFlyAndISwim {
fly () {
console.log('我会飞了')
return '哈哈哈'
}
swim () {
console.log('我会游泳了')
}
}
const person3 = new Person3
person3.fly()
person3.swim()
总结:
接口
和 接口
之间叫 继承(extends)
,接口
和 类
之间叫 实现(implements)
继承多个
、实现多个
时,都是 ,
隔开