简体   繁体   English

TypeScript 管道/组合函数时输入错误

[英]TypeScript typing errors when piping/composing functions

When piping data that varies in type, I receive typing errors.当管道数据类型不同时,我收到输入错误。 How can I satisfy TypeScript?怎样才能满足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. [tsserver 2769] [E] 没有与此调用匹配的重载。最后一次重载出现以下错误。

Argument of type '(x: number) => number' is not assignable to parameter of type '(x: (b: number) => number) => number'. '(x: number) => number' 类型的参数不能分配给'(x: (b: number) => number) => number' 类型的参数。

Types of parameters 'x' and 'x' are incompatible.参数“x”和“x”的类型不兼容。

Type '(b: number) => number' is not assignable to type 'number'.类型 '(b: number) => number' 不可分配给类型 'number'。

I have @types/ramda installed.我安装了@types/ramda

This is an unsatisfying solution, but it does work.这是一个不令人满意的解决方案,但它确实有效。 I temporarily replaced R.add with a locally defined function of simpler type:我暂时将R.add替换为本地定义的更简单类型的 function:

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)
)

Observing the instantiation of R.pipe in your original non-compiling example ( <number, number> ) vs. this simplified example ( <number, number, number, number> ), I realized that TypeScript was incorrectly choosing the curried overload of R.add and getting confused from there. Observing the instantiation of R.pipe in your original non-compiling example ( <number, number> ) vs. this simplified example ( <number, number, number, number> ), I realized that TypeScript was incorrectly choosing the curried overload of R.add并从那里开始感到困惑。 If we explicitly instantiate R.pipe with the correct total arity, the compiler makes the right decision:如果我们使用正确的总参数显式实例化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)
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM