面试题答案
一键面试class Mapper<S, T, F extends (arg: S) => T> {
constructor(private mapFunction: F) {}
map(arr: S[]): T[] {
return arr.map(this.mapFunction);
}
}
类型推断关键步骤解释
- Mapper类定义:
Mapper<S, T, F extends (arg: S) => T>
,这里定义了泛型类Mapper
,它接受三个泛型参数。S
是源类型,T
是目标类型,F
是映射函数类型,且F
函数接受一个S
类型的参数并返回T
类型的值。
- 构造函数:
constructor(private mapFunction: F)
,构造函数接受一个类型为F
的映射函数,并将其存储为类的私有属性mapFunction
。
- map方法:
map(arr: S[]): T[]
,map
方法接受一个S
类型的数组arr
,并返回一个T
类型的数组。return arr.map(this.mapFunction);
,这里使用数组的map
方法,传入类中存储的映射函数mapFunction
。由于mapFunction
的返回值类型被定义为T
,所以整个arr.map(this.mapFunction)
操作返回的数组类型就是T[]
。
- 类型推断:
- 在使用
Mapper
类时,TypeScript会根据传入的映射函数的参数和返回值类型,结合泛型定义,推断出S
和T
的具体类型。例如,若S
是{ id: number, name: string }
,F
是({id}) => id * 2
,因为F
的参数是S
类型,返回值是number
,所以T
会被推断为number
,在map
方法中返回的就是number[]
。
- 在使用