TypeScript一问一答03 类型算法泛型函数

101 阅读1分钟

初篇

你知道泛型函数的基本写法吗?

知道,如下所示

type Identify<Parameter> = Parameter

你知道泛型函数的类型参数吗?

知道, Identify的 Parameter 就是 type parameter(类型参数)

截屏2022-08-20 14.02.29.png

你知道Identify的执行过程吗?

其实就是一个类型算法的替换过程

好的开始进阶吧

进阶

泛型函数的表示方式有几种?

三种

type IdentifyType<Type> = (arg: Type) => Type

interface IdentifyFn<Type> {
  <Type>(arg: Type): Type
}

class IdentifyClass<Type> {
  identify: (arg: Type) => Type
  constructor () {
    this.identify = (arg) => arg
  }
}

你知道联合类型吗?

知道,如下所示

例子1:

type NumOrNul = number | null
type StrOrNul = string | null
type BolOrNul = boolean | null

用泛型函数怎么表达例子1呢?

type paramerter 是 ValueType
例子2:

// 泛型函数的定义
type ValOrNul<ValueType> = ValueType | null

// 泛型函数的实例化
type NumOrNulGeneric = ValOrNul<number>
type StrOrNulGeneric = ValOrNul<string>
type BolOrNulGeneric = ValOrNul<boolean>

// 与 JavaScript 绑定
let num: NumOrNulGeneric = 1
let str: StrOrNulGeneric = 'str'
let bol: BolOrNulGeneric = true


泛型函数的本质是什么?

泛型函数就是可以接受类型参数产生自定义类型的类型算法

 输入<Paramert> => 输出自定义类型

TypeScript中的Array类型怎么表示?


例子3:

const arr: Array<number> = []

arr.push(1)
arr.push('1') // Error

例子3怎么用泛型函数表达吗?


例子4:

type ArrGeneric<Type> = Type[]

type ArrayNumber = ArrGeneric<number>

const arrGeneric: ArrayNumber = []

类数组(array-like type)怎么用泛型函数表达?

如下所示

interface ArrayLike<Type> {
  length: number,
  [key: number]: Type // 扩展符
}

const arrLike: ArrayLike<number> = {0: 0, 1: 1, length: 2}

知道Tuble吗?


例子5:

type TupleType = [string, number]
const tuple1: TupleType = ['1', 1]
tuple1[2] // Error

例子5怎么用泛型函数怎么表示?

type TupleGeneric<X,Y> = [X,Y]
const tuple2: TupleGeneric<string, number> = ['1', 1]

tuple2[2] // Error