关于typescript:typescript接口使用总结

4次阅读

共计 2274 个字符,预计需要花费 6 分钟才能阅读完成。

接口是一系列形象办法的申明,是一些办法特色的汇合,这些办法都应该是形象的,须要由具体的类去实现,而后第三方就能够通过这组形象办法调用,让具体的类执行具体的办法。

一、初识

interface Item { // 定义一个 item 接口
  id: number,
  title: string
}

function renderList(item: Item) {console.log(item.id, item.title); // 1 hello
}

renderList({id: 1, title: 'hello'});

PS:为什么以函数为第一个示例呢?次要是接口在日常的应用大多用来做函数参数应用

二、接口数据类型演示

enum Type {
  Yes = 1,
  No = 0
}

interface Item {
  id: number, // 数字
  title: string, // 字符串
  status: boolean, // 布尔值
  gender: Object, // 对象
  girlfriend: null, // null
  future: undefined, // undefined
  favorites: string[], // 字符串数组
  plan: [string, number], // 元组
  type: Type, // 枚举
  callback: ()=>string, // 返回字符串的回调函数
  // callback(): string, // 函数的另一种写法
  content: any // 任意
}

function renderList(item: Item): void {console.log(item, item.callback());
}

renderList({
  id: 1,
  title: 'hello',
  status: true,
  gender: {1: '男', 0: '女'},
  girlfriend: null,
  future: undefined,
  favorites: ['game', 'movie'],
  plan: ['得分', 100],
  type: Type.Yes,
  callback: () => {return '123123';},
  content: '这是一个内容'
});

三、是否可选

默认属性都是必须的,如果要改成可选的加个? 就行了

interface Item {
  id: number
  title?: string,
}

function renderList(item: Item): void {console.log(item);
}

renderList({id: 1});

四、只读属性

在属性前增加 readonly 修饰符即可表明只读

interface Item {
  id: number,
  readonly title: string
}

let item: Item = {id: 1, title: 'hello'}

item.title = 'world' // 报错

五、接口继承

应用关键字 extends 来实现接口继承

interface Shape {color: string;}

interface Square extends Shape {size: number;}

let square = <Square>{};
square.color = "blue";
square.size = 4;

// 或
// let square: Square = {
//   color: "green",
//   size: 2
// }

console.log(square);

六、接口实现

应用关键字 implements 来实现接口继承

interface ClockInterface {currentTime: Date;}

class Clock implements ClockInterface {currentTime: Date = new Date();
  
  constructor(h: number, m: number) {console.log(h, m, this.currentTime);
  }
}

let clock = new Clock(8, 10);

七、多种属性类型

如果想要一个属性有几个类型,能够加个 | 距离

interface Shape {type: number|string;}

let shape = <Shape>{};
// shape.type = 1;
shape.type = '1';

console.log(shape.type)

八、可索引

次要用来针对数组接口实现

interface StringArray {[index: number]: string;
}

let myArray: StringArray;
myArray = ["Foo", "Bar"];

let myStr: string = myArray[0];
console.log(myStr)

九、混合类型

事实生产可能须要一个对象能够同时做为函数和对象应用,并带有额定的属性,这时就能够应用混合类型

interface Counter {(start: number): string;
  interval: number;
  reset(): void;}

function getCounter(): Counter {let counter = <Counter>function (start: number) {return ` 开始工夫为:${start}`;
  };
  counter.interval = 123;
  counter.reset = function () {};

  return counter;
}

let c = getCounter();
console.log(c(10)); // 开始工夫为:10
c.reset();
c.interval = 5.0;

欢送关注:https://fenxianglu.cn/

参考链接:

  • https://www.tslang.cn/docs/ha…
正文完
 0