前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >被迫开始学习Typescript —— interface

被迫开始学习Typescript —— interface

作者头像
用户1174620
发布2022-05-15 09:05:25
2780
发布2022-05-15 09:05:25
举报
文章被收录于专栏:更流畅、简洁的软件开发方式

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

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

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

简单接口

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

代码语言:javascript
复制
interface Person {
  name: string,
  age: number
}

用接口定义一个对象

代码语言:javascript
复制
const jim: Person = {
  name: 'jyk',
  age: 18
}

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

嵌套的情况

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

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

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

数组和索引

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

  • 数组的方式
代码语言:javascript
复制
interface Person {
  name: string,
  age: number,
  roles: Array<Role>
}
  • 索引的方式
代码语言:javascript
复制
interface Person {
  name: string,
  age: number,
  roles: {
    [index: number | string ]: Role
  }
}

可以有其他任何属性

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

代码语言:javascript
复制
interface SquareConfig {
    color: string;
    width: number;
    [propName: string]: any;
}

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

函数类型

代码语言:javascript
复制
interface SearchFunc {
  (source: string, subString: string): boolean;
}

定义参数和返回类型。

接口的合并

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

代码语言:javascript
复制
interface StateOption {
  isLocal?: boolean, 
  isLog?: boolean, 
  level?: number
}

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


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

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

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

接口继承接口

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

代码语言:javascript
复制
interface Customer extends Person, 其他接口 {
  phone: string
}

类继承(实现)接口

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

代码语言:javascript
复制
class Customer extends Person, 其他接口 {
  phone: string
}

接口继承类

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

代码语言:javascript
复制
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。
  • 既有约束,也有一定的灵活性。
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-05-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 简单接口
  • 嵌套的情况
  • 数组和索引
  • 可以有其他任何属性
  • 函数类型
  • 接口的合并
  • 接口继承接口
  • 类继承(实现)接口
  • 接口继承类
  • 小结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档