TypeScript中如何在泛型类型参数上调用对应静态方法
问题解决方法
你当前的写法存在两个核心问题:
- 你定义的
Type extends Point & Line约束的是类的实例类型,而fromHash是静态方法,挂载在类的构造函数上,不属于实例类型的属性范围,因此不可能直接通过泛型参数Type调用静态方法。 - TypeScript的泛型仅在编译阶段做类型校验,运行时会被完全抹除,你写的
Type.fromHash在运行时根本找不到对应的Type变量,必然会报错。
正确实现方案
将对应类的构造函数作为参数传入函数即可,具体实现如下:
首先定义构造函数的类型约束,确保传入的类一定存在fromHash静态方法:
// 约束:构造函数必须带有fromHash静态方法 interface HashConstructable<T> { fromHash(data: unknown): T; new (...args: any[]): T; } class Point { static fromHash(hash: any) { // Point专属逻辑 return new Point() } } class Line { static fromHash(hash: any) { // Line专属逻辑 return new Line() } }
改写filterIdentical函数,把类构造函数作为第一个入参传入:
const filterIdentical = <T>(Clazz: HashConstructable<T>, array: T[]): T[] => { // 原有计算逻辑 // 直接通过传入的构造函数调用对应类的静态方法 return array.map(item => Clazz.fromHash(item)) }
调用时直接传入对应的类即可,TypeScript会自动推导返回值类型:
const points: Point[] = [] const filteredPoints = filterIdentical(Point, points) // 返回值类型自动推导为Point[] const lines: Line[] = [] const filteredLines = filterIdentical(Line, lines) // 返回值类型自动推导为Line[]
如果你不想每次调用都传入类,可以针对不同类型封装独立的快捷调用函数:
const filterIdenticalPoint = (array: Point[]) => filterIdentical(Point, array) const filterIdenticalLine = (array: Line[]) => filterIdentical(Line, array)
内容的提问来源于stack exchange,提问作者JameEnder
相关产品推荐
相关产品推荐

