You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中如何为泛型函数引用添加类型提示?

解决TypeScript中泛型恒等函数配合fp-ts foldMap的类型推断问题

先看基础的泛型恒等函数:

const identity = <A>(a: A) => a;

调用时TypeScript能自动推断类型参数A:

declare const baz: string;

const foo = identity("bar"); // A = "bar", typeof foo = "bar"
const bar = identity(baz);   // A = string, typeof bar = string

但使用fp-ts的foldMap时,直接传入identity会触发类型错误:

import { foldMap } from "fp-ts/Array";
import { getMonoidAll, Predicate } from "fp-ts/Predicate";

declare const predicates: Predicate<string>[];

// 报错:类型“A”无法赋值给类型“Predicate<string>”
const concatPredicates = foldMap(getMonoidAll<string>())(identity);

这是因为TypeScript对foldMap(getMonoidAll<string>())的类型推断结果是:

typeof foldMap(getMonoidAll<string>()) = <A>(f: (a: A) => Predicate<string>) => 
(fa: A[]) => Predicate<string>

它没能自动识别当A = Predicate<string>时,identity完全符合(a: Predicate<string>) => Predicate<string>的类型签名。


解决方案

1. 显式指定identity的类型参数

直接给identity传入具体的类型参数,明确告知TypeScript目标类型,完全利用identity的泛型特性:

const concatPredicates = foldMap(getMonoidAll<string>())(identity<Predicate<string>>);

2. 使用类型断言缩小范围

如果觉得尖括号写法不够直观,也可以用类型断言指定identity的类型签名:

const concatPredicates = foldMap(getMonoidAll<string>())(identity as (a: Predicate<string>) => Predicate<string>);

3. 极简箭头函数辅助推断

用更简洁的箭头函数替代冗余写法,借助上下文让TypeScript自动推断:

const concatPredicates = foldMap(getMonoidAll<string>())(a => identity(a));

这种写法比完整声明参数类型更简洁,同时能触发正确的类型推断。


内容的提问来源于stack exchange,提问作者Yakmiras

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 17:40:55