服务器之家:专注于服务器技术及软件下载分享
分类导航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服务器之家 - 编程语言 - JavaScript - 你不知道的 TypeScript 高级类型(小结)

你不知道的 TypeScript 高级类型(小结)

2021-09-02 17:27Shenfq JavaScript

这篇文章主要介绍了你不知道的 TypeScript 高级类型(小结),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

前言

对于有 JavaScript 基础的同学来说,入门 TypeScript 其实很容易,只需要简单掌握其基础的类型系统就可以逐步将 JS 应用过渡到 TS 应用。

  1. // js
  2. const double = (num) => 2 * num
  3.  
  4. // ts
  5. const double = (num: number): number => 2 * num

然而,当应用越来越复杂,我们很容易把一些变量设置为 any 类型,TypeScript 写着写着也就成了 AnyScript。为了让大家能更加深入的了解 TypeScript 的类型系统,本文将重点介绍其高级类型,帮助大家摆脱 AnyScript。

泛型

在讲解高级类型之前,我们需要先简单理解泛型是什么。

泛型是强类型语言中比较重要的一个概念,合理的使用泛型可以提升代码的可复用性,让系统更加灵活。下面是维基百科对泛型的描述:

泛型允许程序员在强类型程序设计语言中编写代码时使用一些以后才指定的类型,在实例化时作为参数指明这些类型。

泛型通过一对尖括号来表示( <> ),尖括号内的字符被称为 类型变量 ,这个变量用来表示类型。

  1. function copy<T>(arg: T): T {
  2. if (typeof arg === 'object') {
  3. return JSON.parse(
  4. JSON.stringify(arg)
  5. )
  6. } else {
  7. return arg
  8. }
  9. }

这个类型 T,在没有调用 copy 函数的时候并不确定,只有调用 copy 的时候,我们才知道 T 具体代表什么类型。

  1. const str = copy<string>('my name is typescript')

你不知道的 TypeScript 高级类型(小结)

我们在 VS Code 中可以看到 copy 函数的参数以及返回值已经有了类型,也就是说我们调用 copy 函数的时候,给类型变量 T 赋值了 string。其实,我们在调用 copy 的时候可以省略尖括号,通过 TS 的类型推导是可以确定 T 为 string 的。

你不知道的 TypeScript 高级类型(小结)

高级类型

除了 string、number、boolean 这种基础类型外,我们还应该了解一些类型声明中的一些高级用法。

交叉类型(&)

交叉类型说简单点就是将多个类型合并成一个类型,个人感觉叫做「合并类型」更合理一点,其语法规则和逻辑 “与” 的符号一致。

T & U

假如,我现在有两个类,一个按钮,一个超链接,现在我需要一个带有超链接的按钮,就可以使用交叉类型来实现。

  1. interface Button {
  2. type: string
  3. text: string
  4. }
  5.  
  6. interface Link {
  7. alt: string
  8. href: string
  9. }
  10.  
  11. const linkBtn: Button & Link = {
  12. type: 'danger',
  13. text: '跳转到百度',
  14. alt: '跳转到百度',
  15. href: 'http://www.baidu.com'
  16. }

联合类型(|)

联合类型的语法规则和逻辑 “或” 的符号一致,表示其类型为连接的多个类型中的任意一个。

T | U

例如,之前的 Button 组件,我们的 type 属性只能指定固定的几种字符串。

  1. interface Button {
  2. type: 'default' | 'primary' | 'danger'
  3. text: string
  4. }
  5.  
  6. const btn: Button = {
  7. type: 'primary',
  8. text: '按钮'
  9. }

类型别名(type)

前面提到的交叉类型与联合类型如果有多个地方需要使用,就需要通过类型别名的方式,给这两种类型声明一个别名。类型别名与声明变量的语法类似,只需要把 constlet 换成 type 关键字即可。

type Alias = T | U

  1. type InnerType = 'default' | 'primary' | 'danger'
  2.  
  3. interface Button {
  4. type: InnerType
  5. text: string
  6. }
  7.  
  8. interface Alert {
  9. type: ButtonType
  10. text: string
  11. }

类型索引(keyof)

keyof 类似于 Object.keys ,用于获取一个接口中 Key 的联合类型。

  1. interface Button {
  2. type: string
  3. text: string
  4. }
  5.  
  6. type ButtonKeys = keyof Button
  7. // 等效于
  8. type ButtonKeys = "type" | "text"

还是拿之前的 Button 类来举例,Button 的 type 类型来自于另一个类 ButtonTypes,按照之前的写法,每次 ButtonTypes 更新都需要修改 Button 类,如果我们使用 keyof 就不会有这个烦恼。

  1. interface ButtonStyle {
  2. color: string
  3. background: string
  4. }
  5. interface ButtonTypes {
  6. default: ButtonStyle
  7. primary: ButtonStyle
  8. danger: ButtonStyle
  9. }
  10. interface Button {
  11. type: 'default' | 'primary' | 'danger'
  12. text: string
  13. }
  14.  
  15. // 使用 keyof 后,ButtonTypes修改后,type 类型会自动修改
  16. interface Button {
  17. type: keyof ButtonTypes
  18. text: string
  19. }

类型约束(extends)

这里的 extends 关键词不同于在 class 后使用 extends 的继承作用,泛型内使用的主要作用是对泛型加以约束。我们用我们前面写过的 copy 方法再举个例子:

  1. type BaseType = string | number | boolean
  2.  
  3. // 这里表示 copy 的参数
  4. // 只能是字符串、数字、布尔这几种基础类型
  5. function copy<T extends BaseType>(arg: T): T {
  6. return arg
  7. }

你不知道的 TypeScript 高级类型(小结)

如果我们传入一个对象就会有问题。

你不知道的 TypeScript 高级类型(小结)

extends 经常与 keyof 一起使用,例如我们有一个方法专门用来获取对象的值,但是这个对象并不确定,我们就可以使用 extendskeyof 进行约束。

  1. function getValue<T, K extends keyof T>(obj: T, key: K) {
  2. return obj[key]
  3. }
  4.  
  5. const obj = { a: 1 }
  6. const a = getValue(obj, 'a')

你不知道的 TypeScript 高级类型(小结)

这里的 getValue 方法就能根据传入的参数 obj 来约束 key 的值。

类型映射(in)

in 关键词的作用主要是做类型的映射,遍历已有接口的 key 或者是遍历联合类型。下面使用内置的泛型接口 Readonly 来举例。

  1. type Readonly<T> = {
  2. readonly [P in keyof T]: T[P];
  3. };
  4.  
  5. interface Obj {
  6. a: string
  7. b: string
  8. }
  9.  
  10. type ReadOnlyObj = Readonly<Obj>

你不知道的 TypeScript 高级类型(小结)

我们可以结构下这个逻辑,首先 keyof Obj 得到一个联合类型 'a' | 'b'

  1. interface Obj {
  2. a: string
  3. b: string
  4. }
  5.  
  6. type ObjKeys = 'a' | 'b'
  7.  
  8. type ReadOnlyObj = {
  9. readonly [P in ObjKeys]: Obj[P];
  10. }

然后 P in ObjKeys 相当于执行了一次 forEach 的逻辑,遍历 'a' | 'b'

  1. type ReadOnlyObj = {
  2. readonly a: Obj['a'];
  3. readonly b: Obj['b'];
  4. }

最后就可以得到一个新的接口。

  1. interface ReadOnlyObj {
  2. readonly a: string;
  3. readonly b: string;
  4. }

条件类型(U ? X : Y)

条件类型的语法规则和三元表达式一致,经常用于一些类型不确定的情况。

T extends U ? X : Y

上面的意思就是,如果 T 是 U 的子集,就是类型 X,否则为类型 Y。下面使用内置的泛型接口 Extract 来举例。

  1. type Extract<T, U> = T extends U ? T : never;

如果 T 中的类型在 U 存在,则返回,否则抛弃。假设我们两个类,有三个公共的属性,可以通过 Extract 提取这三个公共属性。

  1. interface Worker {
  2. name: string
  3. age: number
  4. email: string
  5. salary: number
  6. }
  7.  
  8. interface Student {
  9. name: string
  10. age: number
  11. email: string
  12. grade: number
  13. }
  14.  
  15. type CommonKeys = Extract<keyof Worker, keyof Student>
  16. // 'name' | 'age' | 'email'

你不知道的 TypeScript 高级类型(小结)

工具泛型

TypesScript 中内置了很多工具泛型,前面介绍过 ReadonlyExtract 这两种,内置的泛型在 TypeScript 内置的 lib.es5.d.ts 中都有定义,所以不需要任何依赖都是可以直接使用的。下面看看一些经常使用的工具泛型吧。

你不知道的 TypeScript 高级类型(小结)

Partial

  1. type Partial<T> = {
  2. [P in keyof T]?: T[P]
  3. }

Partial 用于将一个接口的所有属性设置为可选状态,首先通过 keyof T ,取出类型变量 T 的所有属性,然后通过 in 进行遍历,最后在属性后加上一个 ?

我们通过 TypeScript 写 React 的组件的时候,如果组件的属性都有默认值的存在,我们就可以通过 Partial 将属性值都变成可选值。

  1. import React from 'react'
  2.  
  3. interface ButtonProps {
  4. type: 'button' | 'submit' | 'reset'
  5. text: string
  6. disabled: boolean
  7. onClick: () => void
  8. }
  9.  
  10. // 将按钮组件的 props 的属性都改为可选
  11. const render = (props: Partial<ButtonProps> = {}) => {
  12. const baseProps = {
  13. disabled: false,
  14. type: 'button',
  15. text: 'Hello World',
  16. onClick: () => {},
  17. }
  18. const options = { ...baseProps, ...props }
  19. return (
  20. <button
  21. type={options.type}
  22. disabled={options.disabled}
  23. onClick={options.onClick}>
  24. {options.text}
  25. </button>
  26. )
  27. }

Required

  1. type Required<T> = {
  2. [P in keyof T]-?: T[P]
  3. }

Required 的作用刚好与 Partial 相反,就是将接口中所有可选的属性改为必须的,区别就是把 Partial 里面的 ? 替换成了 -?

Record

  1. type Record<K extends keyof any, T> = {
  2. [P in K]: T
  3. }

Record 接受两个类型变量, Record 生成的类型具有类型 K 中存在的属性,值为类型 T。这里有一个比较疑惑的点就是给类型 K 加一个类型约束, extends keyof any ,我们可以先看看 keyof any 是个什么东西。

你不知道的 TypeScript 高级类型(小结)

大致一直就是类型 K 被约束在 string | number | symbol 中,刚好就是对象的索引的类型,也就是类型 K 只能指定为这几种类型。

我们在业务代码中经常会构造某个对象的数组,但是数组不方便索引,所以我们有时候会把对象的某个字段拿出来作为索引,然后构造一个新的对象。假设有个商品列表的数组,要在商品列表中找到商品名为 「每日坚果」的商品,我们一般通过遍历数组的方式来查找,比较繁琐,为了方便,我们就会把这个数组改写成对象。

  1. interface Goods {
  2. id: string
  3. name: string
  4. price: string
  5. image: string
  6. }
  7.  
  8. const goodsMap: Record<string, Goods> = {}
  9. const goodsList: Goods[] = await fetch('server.com/goods/list')
  10.  
  11. goodsList.forEach(goods => {
  12. goodsMap[goods.name] = goods
  13. })

Pick

  1. type Pick<T, K extends keyof T> = {
  2. [P in K]: T[P]
  3. }

Pick 主要用于提取接口的某几个属性。做过 Todo 工具的同学都知道,Todo工具只有编辑的时候才会填写描述信息,预览的时候只有标题和完成状态,所以我们可以通过 Pick 工具,提取 Todo 接口的两个属性,生成一个新的类型 TodoPreview。

  1. interface Todo {
  2. title: string
  3. completed: boolean
  4. description: string
  5. }
  6.  
  7. type TodoPreview = Pick<Todo, "title" | "completed">
  8.  
  9. const todo: TodoPreview = {
  10. title: 'Clean room',
  11. completed: false
  12. }

你不知道的 TypeScript 高级类型(小结)

Exclude

  1. type Exclude<T, U> = T extends U ? never : T

Exclude 的作用与之前介绍过的 Extract 刚好相反,如果 T 中的类型在 U 不存在,则返回,否则抛弃。现在我们拿之前的两个类举例,看看 Exclude 的返回结果。

  1. interface Worker {
  2. name: string
  3. age: number
  4. email: string
  5. salary: number
  6. }
  7.  
  8. interface Student {
  9. name: string
  10. age: number
  11. email: string
  12. grade: number
  13. }
  14.  
  15. type ExcludeKeys = Exclude<keyof Worker, keyof Student>
  16. // 'name' | 'age' | 'email'

你不知道的 TypeScript 高级类型(小结)

取出的是 Worker 在 Student 中不存在的 salary

Omit

  1. type Omit<T, K extends keyof any> = Pick<
  2. T, Exclude<keyof T, K>
  3. >

Omit 的作用刚好和 Pick 相反,先通过 Exclude<keyof T, K> 先取出类型 T 中存在,但是 K 不存在的属性,然后再由这些属性构造一个新的类型。还是通过前面的 Todo 案例来说,TodoPreview 类型只需要排除接口的 description 属性即可,写法上比之前 Pick 精简了一些。

  1. interface Todo {
  2. title: string
  3. completed: boolean
  4. description: string
  5. }
  6.  
  7. type TodoPreview = Omit<Todo, "description">
  8.  
  9. const todo: TodoPreview = {
  10. title: 'Clean room',
  11. completed: false
  12. }

你不知道的 TypeScript 高级类型(小结)

总结

如果只是掌握了 TypeScript 的一些基础类型,可能很难游刃有余的去使用 TypeScript,而且最近 TypeScript 发布了 4.0 的版本新增了更多功能,想要用好它只能不断的学习和掌握它。希望阅读本文的朋友都能有所收获,摆脱 AnyScript。

到此这篇关于你不知道的 TypeScript 高级类型(小结)的文章就介绍到这了,更多相关TypeScript 高级类型内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://juejin.im/post/6865860467307315207

延伸 · 阅读

精彩推荐