美文网首页
不理解Typescript泛型?看完就理解了

不理解Typescript泛型?看完就理解了

作者: Kagashino | 来源:发表于2020-04-17 17:11 被阅读0次

如何理解泛型

泛型(Generic Type)存在于许多编程语言中,许多刚接触Typescript且没有Java、C++等带泛型的语言使用经验的程序员,理解起来会有一定的难度,特此开文扫盲

我们再来定义一个盒子box,盒子有number类型的id,而data是任意类型,你可能会想到any

interface Box {
  id: number,
  data: any
}

然而any一时爽,对后期的阅读和分析大为不利。
来看看使用泛型的方式,只要在头部使用尖括号<T>,代码块中使用T来表示类型即可:

interface Box<T> {
    id: number,
    data: T
}

使用带有泛型的Box的时候,我们再传入具体的值:

const box1: Box<string> = {
    id: 1,
    data: 'this is string box'
}

const box2: Box<boolean> = {
    id: 2,
    data: false
}

我们类比一个函数:

function square(a) {
  return a*a
}

上面的泛型<T>,类似于square函数中的形参a, 定义时用来表示宽泛、不确定的值(类型),使用的时候再传入具体的值(类型)

sum(4) // 16

我们可以将泛型理解为: 参数化的类型
有了泛型,我们可以更加具体地描述一个不确定的类型。与any相比,泛型更具有约束力。

泛型的具体用法

上面提到了interface使用泛型的方法,下面将会介绍泛型的其他应用场景

在function/type/class中使用泛型:

泛型可以在function/type/class中声明。
还是以Box举例,type的泛型长得跟interface的基本一样

type Box<B> {
  id: number,
  value: B
}

写一个函数,让一个值变成Box类型:

function toBox<B>(value: B) {
  return {
    id: new Date().getTime(),
    value: value
  }
} 

const box3: Box<string> = toBox('string box')
const box4: Box<number[]> = toBox([1,2,3,4,5])

写一个class,把这个Box用class封装起来:

class MyBox<B> {
  private id: number;
  private value: B;

  public static from<B> (value: B) {
    return new MyBox(value)
  }
  constructor () {
      this.id = new Date().getTime();
      this.value = value;
  }
  // 只允许修改成相同类型的value
  public setValue(value: B): void {
    this.value = value;
  }

  public getValue(): B {
    return this.value;
  }
}

定义多个泛型

这次我们定义一个抽屉,抽屉有三层,三层可以放三种数据

type Drawer<L1, L2, L3> = [L1, L2, L3];
const myDrawer<string, string, string> = ['香烟', '茶叶', '啤酒']

如果一个React项目使用了TypeScript,那么组件可以接受Props泛型和State泛型

type CountProps = {
  initValue: number,
  step?: number
}

type CountState = {
  value: number
}
class Counter extends React.component<CountProps, CountState> {
  constructor(props) {
    super(props)
    this.state = {
      value: props.initValue || 0
    } 
  }
  // 以下略
}

默认泛型

如果某个泛型有默认值,使用的时候不传入类型即为默认值:

type Box<S = string> {
  id: number,
  value: S
}

var boxDefault: Box = { id: 6, value: 'default generic' }
var boxNumber: Box<number> = { id: 7, value: 3.1416 }

原生泛型的应用

Array

这个是最好理解的了,如果想定义一个类型固定的数组除了type[]外还可以使用泛型的方式:

const bools: Array<boolean> = [true, false, true, true, true]

const queue = Array<{id: number, value: string }> = [
  { id: 1, value: 'a' },
  { id: 2, value: 'b' },
  { id: 3, value: 'c' },
]

type[]相比,如果定义一个带有键值类型的数组,使用Array泛型可读性会更高

Set和Map

const plants: Set<string> = new Set()

fruits.add('豌豆射手')
fruits.add('向日葵')
fruits.add('西瓜投手')
fruits.add('玉米大炮')

const subject: Map<string, number> = new Map()

subject.add('语文', 91)
subject.add('数学', 100)
subject.add('英语', 92)
subject.add('政治', 96)

Promise

type UserData = {
  id: number,
  name: string,
  age: number
}

function fetchData(): Promise<UserData> {
  return fetch('/userData').then(res => res.json())
}

async function fetchFollowList (): Promise<UserData> {
  const { id } = await fetchData();
  return fetch(`/follows/${id}`).then(res => res.json())
}

相关文章

  • 不理解Typescript泛型?看完就理解了

    如何理解泛型 泛型(Generic Type)存在于许多编程语言中,许多刚接触Typescript且没有Java、...

  • 2020-11-05Typescript(2.2)

    泛型 Generics---typeScript中最难的一部分 泛型 Generics---约束泛型 泛型 Gen...

  • TS 泛型+装饰器

    typescript 中的泛型 泛型的定义泛型函数泛型类泛型接口 泛型:软件工程中,我们不仅要创建一致的定义良好的...

  • bunny笔记|TS基础(2):泛型函数、泛型约束、在泛型约束中

    01 typescript的操纵类型 02 03 04 泛型约束 05 在泛型约束中使用类型参数 06 在泛型中使...

  • 03_TypeScript学习(三)

    一. TypeScript枚举类型 二. 枚举类型的值 三. 认识泛型 四. 泛型实现类型参数化 五. 泛型的基本...

  • TypeScript 学习笔记4 泛型

    1.泛型 1.1 泛型函数 1.2 泛型类 1.3 泛型接口 Typescript从0到1-学习视频教程-培训课程...

  • typescript

    title: typescript学习tags: typescript学习 [toc] 泛型 基本使用 两种使用方...

  • TypeScript 泛型

    泛型函数 使用 数组 类 泛型约束

  • TypeScript泛型

    有时候编程还要考虑它的复用性,很多时候不需要指定它的类型,或者同样的方法逻辑 但是入参和出差的类型不同。这个时候就...

  • TypeScript(泛型)

    泛型 软件工程中,我们不仅要创建一致的定义良好的API,同时也要考虑可重用性。 组件不仅能够支持当前的数据类型,同...

网友评论

      本文标题:不理解Typescript泛型?看完就理解了

      本文链接:https://www.haomeiwen.com/subject/dcyvrhtx.html