当前位置:
首页
文章
前端
详情

typescript接口使用总结

接口是一系列抽象方法的声明,是一些方法特征的集合,这些方法都应该是抽象的,需要由具体的类去实现,然后第三方就可以通过这组抽象方法调用,让具体的类执行具体的方法。

一、初识

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: (name: string)=>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: (name) => {
    return name + '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://www.tslang.cn/docs/handbook/interfaces.html

免责申明:本站发布的内容(图片、视频和文字)以转载和分享为主,文章观点不代表本站立场,如涉及侵权请联系站长邮箱:xbc-online@qq.com进行反馈,一经查实,将立刻删除涉嫌侵权内容。