CustomError类型的参数不能分配给Typescript中的Error

时间:2015-07-30 19:44:50

标签: 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的蓝鸟承诺。

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

1 个答案:

答案 0 :(得分:7)

问题是lib.d.tsError声明为接口和变量,而不是类。

选项1。实施Error界面并通过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