我正在构建一个函数,接受一个函数链,其中每个函数都会转换前一个函数的结果。在给定的示例中,
这是代码 (TypeScript playground):
当数组中只有一个函数时,TypeScript可以正确推断类型,即使示例更复杂并具有初始状态。(完整错误信息请参见TypeScript playground)。
_context
应该等于 { hello: 'world', something: 'else' }
:function withWorld<Context extends {}>(context: Context) {
return { ...context, hello: 'world' }
}
function withSomething<Context extends {}>(context: Context) {
return { ...context, something: 'else' }
}
test([withWorld, withSomething], (_context) => {})
然而,当我试图使用泛型来描述这个行为时,我遇到了一个错误:
No overload matches this call:
Types of parameters 'contextSomething' and 'contextB' are incompatible.
Type 'unknown' is not assignable to type '{}'.
这是代码 (TypeScript playground):
export interface TestFunction {
<A>(
conditions: [(contextSolo: {}) => A],
body: (contextBodySolo: A) => any
): any
<A, B>(
conditions: [(contextA: {}) => A, (contextB: A) => B],
body: (contextBody: B) => void
): any
}
const test: TestFunction = () => void 0
function withWorld<Context extends {}>(contextWithWorld: Context) {
return { ...context, hello: 'world' }
}
function withSomething<Context extends {}>(contextSomething: Context) {
return { ...context, something: 'else' }
}
test([withSomething], (_context) => {})
test([withWorld], (_context) => {})
test([withWorld, withSomething], (_context) => {})
当数组中只有一个函数时,TypeScript可以正确推断类型,即使示例更复杂并具有初始状态。(完整错误信息请参见TypeScript playground)。
No overload matches this call.
Overload 1 of 2, '(conditions: [(contextSolo: {}) => any], body: (contextBodySolo: any) => any): any', gave the following error.
Argument of type '[<Context extends {}>(contextWithWorld: Context) => any, <Context extends {}>(contextSomething: Context) => any]' is not assignable to parameter of type '[(contextSolo: {}) => any]'.
Source has 2 element(s) but target allows only 1.
Overload 2 of 2, '(conditions: [(contextA: {}) => unknown, (contextB: unknown) => any], body: (contextBody: any) => void): any', gave the following error.
Type '<Context extends {}>(contextSomething: Context) => any' is not assignable to type '(contextB: unknown) => any'.
Types of parameters 'contextSomething' and 'contextB' are incompatible.
Type 'unknown' is not assignable to type '{}'.(2769)