I have the following example interface/class
export interface MyErrorI {
something: boolean;
}
export class MyError extends Error implements MyErrorI {
public something = false;
constructor(message: string, key: keyof MyErrorI ) {
super(message);
this[key] = true; // this is the code that I want to reuse
}
}
The concept is that the constructor sets the value of its properties based on its key param.
Now I want to extend it with another class:
interface MyNewErrorI extends MyErrorI {
somethingElse: boolean;
}
export class MyNewError extends MyError implements MyNewErrorI {
public somethingElse = false;
constructor(message: string, key: keyof MyNewErrorI) {
super(message, key);
}
}
Now, the key param can have a property of the interface which extends MyErrorI. I don't want to copy/paste the code from the parent class' constructor to the child class' constructor, due to its complexity in my actual problem.
However, the code above can't work because the constructor of MyError expects a key of MyErrorI. However, the key somethingElse is a valid property of MyNewError.
So, the question is: Is it possible that the parent class' constructor accesses the key param, each time based on its child class that calls super?
I tried to do something like this, but it didn't work either:
export class MyError<T extends PaymentErrorI> extends Error implements MyErrorI {
public something = false;
constructor(message: string, key: keyof T) {
super(message);
this[key] = true;
}
}
The actual constructor is the following:
constructor(message: string, key: keyof MyErrorI | Array<keyof MyErrorI>, data?: any) {
super(message);
if (key instanceof Array) {
key.forEach((v) => {
this[v] = true;
});
} else {
this[key] = true;
}
this.payload = data;
}
So calling it using super(message, key, data) saves more lines of code, and makes it more maintainable.
Alternatively, could I use a function which has the same functionality? Something like
const setKeys = <T>(err: T, key: keyof T | Array<keyof T>)
which would provide the functionality needed. Like this, for err[key] = true I get Type 'true' is not assignable to type 'T[keyof T]'
Thanks in advance!