TS2345:X 类型的参数不可分配给 Y 类型的参数

TS2345: Argument of type X is not assignable to parameter of type Y

TypeScript 出现奇怪的错误:

如图所示,错误是:

TS2345: Argument of type 'ErrnoException' is not assignable to parameter of type '(err: ErrnoException) => void'. Type 'ErrnoException' provides no match for the signature '(err: ErrnoException): void'.

这是导致错误的代码:

export const bump = function(cb: ErrnoException){
  const {pkg, pkgPath} = syncSetup();
  fs.writeFile(pkgPath, JSON.stringify(pkg, null, 2), cb);
};

有人知道这是怎么回事吗?

您正在发送类型为 ErrnoException 的值,而您正在调用的函数需要一个采用 *ErrnoException** 和 returns 类型参数的函数无效。

您发送:

let x = new ErrnoException;

虽然您调用的函数需要

let cb = function(e: ErrnoException) {};

您可以像这样更改函数以接收正确的参数。

export const bump = function(cb: (err: ErrnoException) => void){
  const {pkg, pkgPath} = syncSetup();
  fs.writeFile(pkgPath, JSON.stringify(pkg, null, 2), cb);
};