TypeScript 学习实战-6-interface("接口")

326 阅读3分钟

这是我参与11月更文挑战的第19天,活动详情查看:2021最后一次更文挑战

前言

现在 TypeScript + Vue3 应用特别广了, 如果不学习, 总感觉跟不上大厂的步伐了. 学习 TypeScript(虽然觉得也是可选的,但还是要学,真卷...) 这里记录学习 TypeScript 的过程, 收录在 TypeScript 实战专栏

回顾上一篇: 学习了 TS 的枚举类型/ 枚举类型概念及分类/ 数字枚举 举例以及枚举类型的使用方法.

本文来学习 TS 中应用还是比较多的 interface 接口

1. Typescript 文档

Typescript 官网地址: typescriptlang.org/zh/

Typescript 中文文档--接口:interfaces-接口

TypeScript 接口 interface

此 "接口" 非彼 "接口"! 这里的 "接口" interface 并不是我们向后端请求的接口 e.

TypeScript 的核心原则之一是对值所具有的结构进行类型检查。 在 TypeScript 里,接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约。

通过代码来理解

这里定义一个 用户的相关信息的字段格式. 也就是说 接口实际上就是帮助我们约束一些字段的类型及是否为必需:

export interface UserProps {
  isLogin: boolean
  _id?: string
  nickName?: string
  email?: string
  avatar?: ImageProps
  description?: string
  column?: string
}

还有 比方我们写了一篇文章, 需要上传时, 请求"后端接口"(注意这里的接口的区别)需要传递的数据字段, 在这里对一些必需字段进行限制, 如果缺少则报错提示

// 要上传文章的 id 标题 内容 图片 创建日期 作者 分类等等 字段
export interface PostProps {
  _id: string
  title: string
  excerpt?: string
  content?: string
  image?: ImageProps | string
  createdAt: string
  column: string
  author?: string
}

接口 可选属性

注意到上面定义的接口的属性中的 ?了吗? 有 ?标记为 可选属性. 帮助我们减少不必要的麻烦..

接口里的属性不全都是必需的。 有些是只在某些条件下存在,或者根本不存在。 可选属性在应用“option bags”模式时很常用,即给函数传入的参数对象中只有部分属性赋值了。

接口 只读属性

一些对象属性只能在对象刚刚创建的时候修改其值。 你可以在属性名前用 readonly来指定只读属性:

interface Point {
    readonly x: number;
    readonly y: number;
}

函数类型

比如上面定义的 用户信息 user 含有一个函数:

user.say = function(words: string) {
    return 'hello world'
}

则在接口中这么来定义:

export interface UserProps {
  isLogin: boolean
  _id?: string
  nickName?: string
  email?: string
  avatar?: ImageProps
  description?: string
  say: (words: string) => string
}

Vue3 学习实战系列更文:

  1. Vue3 源码学习-工具函数 utils(二)
  2. Vue3-初体验,
  3. Vue3-生命周期setup()函数,
  4. Vue3-computed & watch,
  5. Vue3-Teleport 改变组件挂载的根节点,
  6. Vue3-Suspense 处理异步请求,
  7. Vue3-defAsyncComponent 异步组件(新增),
  8. Vue3-fragments (新增),
  9. Vue3-v-model (非兼容),
  1. TypeScript 系列: