为什么我的 typescript 引用我的自定义错误给我错误 Argument of type CustomError is not assignable to parameter of type Error in Typescript
我的错误类
module Errors {
export declare class Error {
public name: string;
public message: string;
public stack: string;
constructor(message?: string);
}
export class CustomError extends Error {
constructor(message: string) {
super(message);
this.name = 'invalid parameters error';
this.message = message || 'the parameters for the request or call are incorrect.';
this.stack = (<any>new Error()).stack;
}
}
}
并在代码中从 Sequelize 返回一个 bluebird promise。
var Promise = require('bluebird');
var import Errors = require('./errors')
//using fs here for an example, it can be any bluebird promise
fs.readFileAsync("file.json").catch(Errors.InvalidParameterError, e => { //this is typescript compiler error
return reply(Boom.badRequest())
})
最佳答案
问题是 lib.d.ts
将 Error
声明为接口(interface)和变量,而不是类。
方案1.实现Error
接口(interface)并通过util.inherits
继承
import util = require('util');
module Errors {
export class CustomError implements Error {
name: string;
message: string;
constructor(message: string) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = 'invalid parameters error';
this.message = message || 'the parameters for the request or call are incorrect.';
}
}
util.inherits(CustomError, Error);
}
export = Errors;
注意,captureStackTrace
没有在默认声明中声明,所以你应该在onw .d.ts
文件中声明它:
interface ErrorConstructor {
captureStackTrace(error: Error, errorConstructor: Function);
}
选项2.不加类糖
module Errors {
export var CustomError = <ErrorConstructor>function (message: string) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
this.name = 'invalid parameters error';
this.message = message || 'the parameters for the request or call are incorrect.';
}
util.inherits(CustomError, Error);
}
选项 3. 纯 TypeScript 方式
声明文件(不需要,因为鸭子打字):
declare type ErrorInterface = Error;
错误模块:
module Errors {
declare class Error implements ErrorInterface {
name: string;
message: string;
static captureStackTrace(object, objectConstructor?);
}
export class CustomError extends Error {
constructor(message: string) {
super();
Error.captureStackTrace(this, this.constructor);
this.name = 'invalid parameters error';
this.message = message || 'the parameters for the request or call are incorrect.';
}
}
}
export = Errors;
同时检查您是否有正确的捕获声明:
catch(e: Error) // wrong
catch(e: { new (message?: string): Error }) // right
关于typescript - CustomError 类型的参数不能分配给 Typescript 中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31732708/