美文网首页
TypeScript中的接口

TypeScript中的接口

作者: _hider | 来源:发表于2020-11-07 21:25 被阅读0次

TypeScript中接口的定义:在面向对象的编程中,接口是一种规范的定义,它定义了行为和动作的规范,在程序设计里面,接口起到一种限制和规范的作用。接口定义了某一批类所需要遵守的规范,接口不关心这些类的内部状态数据,也不关心这些类里方法的实现细节,它只规定这批类里必须提供某些方法,提供这些方法的类就可以满足实际需要。 TypeScript中的接口类似于java,同时还增加了更灵活的接口类型,包括属性、函数、可索引和类等。

TypeScript中的接口有以下四种:

  • 属性类接口
  • 函数类接口
  • 可索引接口
  • 类类型接口
一、属性类接口

属性类接口主要是用作对josn进行约束,描述带有属性的普通对象。

interface Solider {
  name:string;
  age?:number;
};
const Navy : Solider = {}; //Type '{}' is missing the following properties from type 'Solider': name
const Army : Solider = {
  name : 'don',
  age : 18
};

上例中,对Navy变量做了限制,规定必须有name,而age为可选参数。

二、函数类接口

在定义函数类型接口时,需要明确定义函数的参数列表和返回值类型,且参数列表中的每个参数都要有参数名和类型。示例代码如下:

interface Introduce {
  (name:string,age:number):string
};

对传入的参数以及返回值进行约束。

const Solider:Introduce = (name,age)=>{
  return `你好,我的名字叫${name},年龄是${age}岁`;
};
console.log(Solider('don',18)); //你好,我的名字叫don,年龄是18岁
三、可索引接口

可索引接口主要是对数组,对象的约束。

数组的约束

interface ArrType {
  [index:number]:string
};
const arr : ArrType = [1,2]; //Type 'number' is not assignable to type 'string'
const arr : ArrType = ['don','alice'];

以上规定了ArrType接口,即规定键名indexnumber类型,键值为string类型。键名indexnumber类型即为数组,规定了其子元素必须是字符串。

对象的约束

interface ObjType {
  [index:string] : string
};
const obj:ObjType = {
  name:'don'
};

同理数组的约束,规定键名indexstring类型即为对象,上例规定对象的键指必须为字符串。

四、类类型接口

类类型接口是对类的约束,对类约束的还有抽象类。

interface classType {
  name: string;
  introduce( str: string ): void;
};

class Solider implements classType {
  public name:string;
  constructor(name){
    this.name = name;
  };
  introduce(){
    console.log(`hello world ${this.name}`);
  };
};

const don = new Solider("don");
don.introduce();

上例声明了classType接口,规定该类必须包含name属性和introduce方法,并规定了对应的数据类型。

这里有点需要注意的是上例声明Solider没有用extends,而是用的是implements,这里简单介绍下两者的区别:

  • extends表示继承,class A extends C表示声明的A继承自C,而且需要搭配super来使用。
  • implements表示按照接口声明类,class A implements C表示声明的A必须去实现定义在C中的所有方法,无论这些方法是否在类A中有没有默认的实现,也不用在A中定义super方法。

相关文章

网友评论

      本文标题:TypeScript中的接口

      本文链接:https://www.haomeiwen.com/subject/gmdnvktx.html