Exploring how to implement inheritance in Typescript has been an interesting journey. I started by creating a base class Model structured like this:
export class Model {
[key: string]: any;
public errors?: {
[key in keyof Model]: string;
};
constructor(model?: { [key in keyof Model]: Model[key] }) {
if (model) {
Object.assign<Model, Model>(this, model);
}
}
}
After that, I moved on to writing a test file featuring the following code:
import {Model} from './Model';
describe('Model', () => {
class ChildModel extends Model {
public name: string;
}
it('create model from object', () => {
const name: string = 'Test Model';
const childModel: ChildModel = new ChildModel({
name,
});
expect(childModel.name).toEqual(name);
});
});
During my debugging efforts within the base class constructor scope, I noticed that while the input model properties were successfully mapped into the class instance, the child class instance seemed unable to access these mapped properties. Despite researching extensively online and even attempting various strategies like placing the super call as the first line in the child class constructor or creating a default constructor with a super call, the tests continued to fail.
Interestingly, when running the code on CodeSandbox, everything worked perfectly. To witness the error occurring firsthand, please clone this repository and execute yarn test
.