gpt4 book ai didi

typescript - CustomError 类型的参数不能分配给 Typescript 中的错误

转载 作者:搜寻专家 更新时间:2023-10-30 21:16:55 29 4
gpt4 key购买 nike

为什么我的 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.tsError 声明为接口(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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com