อาร์กิวเมนต์ของประเภท CustomError ไม่สามารถกำหนดค่าให้กับ Error ใน Typescript ได้
ทำไมในการอ้างอิง 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;
}
}
}
และในโค้ดที่คืนค่าสัญญา bluebird จาก 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
ปัญหาคือ lib.d.ts ประกาศ Error เป็นอินเทอร์เฟซและตัวแปร แต่ไม่ใช่คลาส
ตัวเลือก 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 ไม่ได้ถูกประกาศในคำประกาศเริ่มต้น ดังนั้นคุณควรประกาศมันในไฟล์ .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 ที่ถูกต้องหรือไม่:
catch(e: Error) // wrong
catch(e: { new (message?: string): Error }) // right
