piping/composing 函数时出现 TypeScript 打字错误
TypeScript typing errors when piping/composing functions
当传输类型不同的数据时,我收到输入错误。如何满足 TypeScript?
const square = (x: number) => x * x
console.log(
R.pipe(
R.add, // two values
square // one value
)(1, 2)
)
[tsserver 2769] [E] No overload matches this call.The last overload
gave the following error.
Argument of type '(x: number) => number' is not assignable to
parameter of type '(x: (b: number) => number) => number'.
Types of parameters 'x' and 'x' are incompatible.
Type '(b: number) => number' is not assignable to type 'number'.
我已经安装了@types/ramda
。
这是一个不令人满意的解决方案,但它确实有效。我暂时将 R.add
替换为本地定义的更简单类型的函数:
const add = (a: number, b: number) => a + b
const square = (x: number) => x * x
console.log(
R.pipe(
add, // two values
square // one value
)(1, 2)
)
观察原始非编译示例 (<number, number>
) 与此简化示例 (<number, number, number, number>
) 中 R.pipe
的实例化,我意识到 TypeScript 错误地选择了 curried R.add
的超载并从那里感到困惑。如果我们用正确的总数显式实例化 R.pipe
,编译器会做出正确的决定:
const square = (x: number) => x * x
console.log(
R.pipe<number, number, number, number>(
R.add, // two values
square // one value
)(1, 2)
)
当传输类型不同的数据时,我收到输入错误。如何满足 TypeScript?
const square = (x: number) => x * x
console.log(
R.pipe(
R.add, // two values
square // one value
)(1, 2)
)
[tsserver 2769] [E] No overload matches this call.The last overload gave the following error.
Argument of type '(x: number) => number' is not assignable to parameter of type '(x: (b: number) => number) => number'.
Types of parameters 'x' and 'x' are incompatible.
Type '(b: number) => number' is not assignable to type 'number'.
我已经安装了@types/ramda
。
这是一个不令人满意的解决方案,但它确实有效。我暂时将 R.add
替换为本地定义的更简单类型的函数:
const add = (a: number, b: number) => a + b
const square = (x: number) => x * x
console.log(
R.pipe(
add, // two values
square // one value
)(1, 2)
)
观察原始非编译示例 (<number, number>
) 与此简化示例 (<number, number, number, number>
) 中 R.pipe
的实例化,我意识到 TypeScript 错误地选择了 curried R.add
的超载并从那里感到困惑。如果我们用正确的总数显式实例化 R.pipe
,编译器会做出正确的决定:
const square = (x: number) => x * x
console.log(
R.pipe<number, number, number, number>(
R.add, // two values
square // one value
)(1, 2)
)