在TypeScript中,有一个重要的内容,接口。提起来接口这个词,我的脑海中就会想起来和后端人员对接时使用的api接口,后端人员在接口文档上,写上请求的方式,请求的api,请求的参数等等;但是此接口非彼接口,但是含义是相近的!

后端人员规定了我需要传递的字段名称,字段类型,一旦前台传递的参数类型不对应,后台代码就会告诉你,我想要的是一个数字,但是你却传递了一个字符串这种错误,相信我们都遇到过!

那么在TypeScript中的接口,其实也是起到了这么的一个作用!

TypeScript的核心原则之一是对值所具有的shape进行类型检查。 它有时被称做“鸭式辨型法”或“结构性子类型化”。
在TypeScript里,接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约。

声明一个接口语法:interface interface_name { }

来定义一个类型,根据此类型来进行值的声明
interface cat { name: string, //string类型 age: number, //number类型 food:
[string], //数组,内部值为string类型 color?: string, //可选属性,string类型;color不是非必须的
readonly gender: string, //只读属性 weight: number | (() => number), //联合类 run():
void, [propName: string]: any; //额外还带有任意数量的其它属性 }
在此接口中,我们定义了各种各样值的类型,属性,下面我们来根据此接口进行值得声明
const catObj: cat = { name: '多拉', age: 1, food: ['小鱼干'], color: '白黄相间',
//可选属性 gender: '母', //只读属性 // weight:10, //联合类型 weight: () => 10, //联合类型 run():
void { console.log(`室内捉老鼠`) }, //以下为额外的属性 aaa: '1212', bbb: 999, ccc: [1, 2,
'3'], ddd: {name: 'he'} } console.log(catObj) // catObj.gender = '公'
//error因为是只读属性,所以直接error;Cannot assign to 'gender' because it is a read-only
property. catObj.run() // console.log(catObj.weight())
//因为我们声明变量的时候关于weight变量使用了函数式的返回值,直接写虽然对运行结果并无影响,但是编译会直接报错,所以需要采用以下写法 let fn:
any = catObj.weight; console.log(fn());
比较需要注意的就是联合类型,当我们声明值得时候采用的是函数时,我们需要进行变量的承接,否则会编译错误!

设置只读属性时,我们将不能改变此属性值

设置可选属性时,我们可写可不写,好处之一是可以对可能存在的属性进行预定义,好处之二是可以捕获引用了不存在的属性时的错误

页面输出:

 接口继承

和类一样,接口也可以进行继承;所谓的接口继承,意思就是可以通过其他接口来扩展自己,在ts中允许接口继承于多个接口,继承的时候使用关键字extends

语法:

单接口继承的语法:Child_interface_name extends super_interface_name

多接口继承语法格式:

Child_interface_name extends   super_interface1_name,super_interface2_name,…
interface Person { age: number } interface Musician extends Person {
instrument: string } const musician1: Musician = { age: 18, instrument: '古筝' }
console.log(musician1)
 Musician接口继承于Person接口,通过Musician接口进行值的定义

页面输出:

 定义类满足定义的接口

需要使用implements关键字,我们首先定义了一个接口,而后根据接口myInter定义了一个抽象类Animal,最后又定义了一个子类Dog,继承于Animal
// 定义接口 interface myInter { name: string age: number say(): void //只能是抽象方法 }
// 定义抽象类,使类满足接口的要求 abstract class Animal implements myInter { age: number;
name: string; constructor(name: string, age: number) { this.name = name
this.age = age } abstract say(): void } // 定义子类Dog,继承于Animal class Dog extends
Animal { say(): string { return '旺旺旺!' } sayHello(): void {
console.log(`${this.name},今年${this.age}岁,每天${this.say()}`) } } const dog = new
Dog('贝拉', 3) console.log(dog) dog.sayHello()
页面输出:

 暂时结束吧!

技术
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信