TypeScript 在类型构造函数中推断回调 return 类型
TypeScript infer the callback return type in type constructor
我想为接收类型 S
和从 S
到另一个类型的函数编写类型构造函数,然后将该函数应用于 S
和 returns 结果:
// 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
参数的 return 类型而不指定 R
?
从 TS3.4 开始,不支持 partial type argument inference,因此您不能轻易让编译器让您指定 S
但推断 R
。但是从您的示例来看,您似乎不想 infer R
作为某种具体类型,但允许它保持通用,以便 return 类型当您 呼叫 d()
.
时,fn
可以是任何它想要的
所以看起来你真的想要这种类型:
type Dig<S> = <R>(s: S, fn: (s: S) => R) => R;
这是一种 "doubly generic" 类型,从某种意义上说,一旦您指定 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
好的,希望对您有所帮助。祝你好运!
我想为接收类型 S
和从 S
到另一个类型的函数编写类型构造函数,然后将该函数应用于 S
和 returns 结果:
// 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
参数的 return 类型而不指定 R
?
从 TS3.4 开始,不支持 partial type argument inference,因此您不能轻易让编译器让您指定 S
但推断 R
。但是从您的示例来看,您似乎不想 infer R
作为某种具体类型,但允许它保持通用,以便 return 类型当您 呼叫 d()
.
fn
可以是任何它想要的
所以看起来你真的想要这种类型:
type Dig<S> = <R>(s: S, fn: (s: S) => R) => R;
这是一种 "doubly generic" 类型,从某种意义上说,一旦您指定 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
好的,希望对您有所帮助。祝你好运!