How can we return custom object in Typescript's class constructor if that class has some required attribute. Below is example snippet for my situation in Typescript.
class MyError extends Error {
customRequiredAttribute: string[];
constructor(error: any) {
if (error instanceof MyError) {
return error;
} else {
// do something else to initialize this instance
super(error);
this.customRequiredAttribute = [error.message];
}
}
}
Please see in the playground.
Above Typescript snippet will produce the following error:
Property 'customRequiredAttribute' has no initializer and is not definitely assigned in the constructor.
While in Javascript, we can achieve that:
class MyError extends Error {
constructor(error) {
if (error instanceof MyError) {
return error;
} else {
// do something else to initialize this instance
super(error);
this.customRequiredAttribute = [error.message];
}
}
}
const MyErrorFromNativeError = new MyError(new Error('has some error'));
const MyErrorFromMyError = new MyError(MyErrorFromNativeError);
console.log("Is both MyError above the same:", MyErrorFromMyError === MyErrorFromNativeError);