javascript - 打字稿功能类型推断
问题描述
我已经编写了这个简单的 compose 函数,它工作得很好。然而,为了确保类型安全,我不得不求助于使用泛型为编译器提供类型提示,即使很容易推断出“upperCaseAndLog”的签名。
const compose = <T, R>(...fns: Array<(a: any) => any>) => (a: T): R =>
fns.reduce((b, f) => f(b), a);
const greet = (s: string) => "Hello " + s;
const toUpperCase = (s: string) => s.toUpperCase();
const log = console.log;
const upperCaseAndLog = compose<string, void>(
greet,
toUpperCase,
log
);
upperCaseAndLog("bill");
我错过了什么吗,有没有更优雅的方式来实现相同的目标?我假设像 F# 或 Haskell 这样的语言能够在没有任何额外信息的情况下推断类型。
解决方案
Typescript 无法推断出这种链接类型(链接的意思是函数的参数取决于前一个函数的结果)。
您甚至无法compose
以足够通用的方式定义签名,使其适用于许多功能。我们可以做的是定义接受最多给定数量的函数的重载:
type Fn<A, R> = (a: A) => R // just to be a bit shorter in the compose signature, you can use teh function signature directly
function compose<T, P1, P2, R>(fn1: Fn<T, P1>, fn2: Fn<P1, P2>, f3: Fn<P2, R>) : Fn<T, R>
function compose<T, P1, R>(fn1: Fn<T, P1>, f2: Fn<P1, R>) : Fn<T, R>
function compose(...fns: Array<(a: any) => any>) {
return function (a: any) {
return fns.reduce((b, f) => f(b), a);
}
}
const greet = (s: string) => "Hello " + s;
const toUpperCase = (s: string) => s.toUpperCase();
const log = console.log;
const upperCaseAndLog = compose(
greet,
toUpperCase,
log
);
upperCaseAndLog("bill");//(a: string) => void
推荐阅读
- python - Pandas:计算一列中的每个值出现在另一列中的次数
- python - 如果列中的值发生更改,则删除行
- python - 使用 Chunksize 和 Dask 在 Pandas with Missingno 中处理 8GB Redshift 表
- nlog - NLog - 每日日志文件 - 如何在触发或创建新日志文件时添加摘要
- python - 如何删除 XML 文件中所有出现的元素?
- python - 在 venv 中通过 bash 运行 python 脚本时出现意外失败
- typescript - 如何为 VS Code 扩展导出的 API 提供类型?
- google-cloud-firestore - FCM 发送给特定用户
- c# - 当客户端是用 .NET Framework 编写时,无法从 IdentittyServer4 获取“名称”声明
- pandas - Pandas 将日期时间列向后移动一小时