代码改变世界

被迫开始学习Typescript —— interface

2022-05-14 10:11  金色海洋(jyk)  阅读(449)  评论(4编辑  收藏  举报

一开始以为,需要使用 class 来定义呢,学习之后才发现,一般都是使用 interface 来定义的。

这个嘛,倒是挺适合 js 环境的。

参考:https://typescript.bootcss.com/interfaces.html

简单接口

我们先来定义一个简单的接口

interface Person {
  name: string,
  age: number
}

用接口定义一个对象

const jim: Person = {
  name: 'jyk',
  age: 18
}

这样编辑器就可以按照接口的定义来检查 jim 是否符合要求。

嵌套的情况

如果是多层的属性怎么办呢?我们可以一起定义,也可以分开定义。

  • 在一起定义(比较直观):
interface Person {
  name: string,
  age: number,
  role: {
    api: string,
    moduleId: number
  }
}
  • 分开定义(可以灵活组合):
interface Role {
  api: string,
  moduleId: number
}

interface Person {
  name: string,
  age: number,
  role: Role
}

数组和索引

如果有多个 role 呢,我们可以用数组的形式,也可以用索引的方式。

  • 数组的方式
interface Person {
  name: string,
  age: number,
  roles: Array<Role>
}
  • 索引的方式
interface Person {
  name: string,
  age: number,
  roles: {
    [index: number | string ]: Role
  }
}

可以有其他任何属性

js 可以很随意,没想到 ts 也可以比较随意。

interface SquareConfig {
    color: string;
    width: number;
    [propName: string]: any;
}

除了指定的属性之外,还可以有其他任意属性。这个嘛。

函数类型

interface SearchFunc {
  (source: string, subString: string): boolean;
}

定义参数和返回类型。

接口的合并

这个嘛,说起来挺奇怪的,虽然是一个我想要的的方式,但是发现真的有这种方式的时候,还是感觉挺诧异的。

interface StateOption {
  isLocal?: boolean, 
  isLog?: boolean, 
  level?: number
}

interface StateCreateOption {
  state?: any,
  getters?: any,
  actions?: any
}


const foo: StateCreateOption & StateOption = {
  isLocal: true, 
  state: {},
}

可以把两个接口合并在一起,约束一个对象,要求有两个接口的属性。

贯彻了 js 世界里的 “组合>继承” 的特点。

接口继承接口

接口除了合并之外,还可以继承接口,支持多继承。

interface Customer extends Person, 其他接口 {
  phone: string
}

类继承(实现)接口

ts 的 class 也可以继承(实现)接口,也支持多继承。

class Customer extends Person, 其他接口 {
  phone: string
}

接口继承类

接口还可以继承类?我也没想到可以这样。

class Control {
    private state: any;
}

interface SelectableControl extends Control {
    select(): void;
}

class Button extends Control implements SelectableControl {
    select() { }
}

class TextBox extends Control {

}

// Error: Property 'state' is missing in type 'Image'.
class Image implements SelectableControl {
    select() { }
}

class Location {

}

是不是挺绕的?好吧,我也没绕出来。

小结

  • 继承 class 使用 extends。
  • 继承 interface 使用 implements。
  • 既有约束,也有一定的灵活性。
2