【发布时间】:2019-09-03 11:01:54
【问题描述】:
我想为一个函数编写一个类型构造函数,该函数接收一个类型 S 和一个来自 S 的函数到另一个类型,然后将该函数应用于 S 并返回结果:
// This works but it's tied to the implementation
function dig<S, R>(s: S, fn: (s: S) => R): R {
return fn(s);
}
// This works as separate type constructor but I have to specify `R`
type Dig<S, R> = (s: S, fn: (s: S) => R) => R;
// Generic type 'Dig' requires 2 type argument(s).
const d: Dig<string> = (s, fn) => fn(s);
那么我如何编写一个Dig<S> 类型构造函数来推断传递的fn 参数的返回类型,而无需我指定R?
【问题讨论】:
标签: typescript generics type-inference