Sam*_*Rad 2 generics type-inference typescript
我想为一个函数编写一个类型构造函数,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);
Run Code Online (Sandbox Code Playgroud)
那么如何编写一个Dig<S>类型构造函数来推断传递fn参数的返回类型而不指定R?
从 TS3.4 开始,不支持部分类型参数推断,因此您不能轻易让编译器让您指定S但推断R。但是从您的示例来看,您似乎不想将其推断 R为某种具体类型,而是允许它保持泛型,以便fn在调用 d().
所以看起来你真的想要这种类型:
type Dig<S> = <R>(s: S, fn: (s: S) => R) => R;
Run Code Online (Sandbox Code Playgroud)
这是一种“双重泛型”类型,从某种意义上说,一旦您指定,S您仍然有一个依赖于R. 这应该适用于您给出的示例:
const d: Dig<string> = (s, fn) => fn(s);
const num = d("hey", (x) => x.length); // num is inferred as number
const bool = d("you", (x) => x.indexOf("z") >= 0); // bool inferred as boolean
Run Code Online (Sandbox Code Playgroud)
好的,希望有帮助。祝你好运!
| 归档时间: |
|
| 查看次数: |
964 次 |
| 最近记录: |