I am new to generics I made a design where we use generic so that it increases code flexiblity. But in my case I have a weird issue where the get the above error. My requirement is that I want to able to pass the value from a child class of a sub class of a base class to the base class to do an operation in the base class and return back the value to the child class. I have attached my code snippet here. playground
Here you can find the error and help me refactor my code so that I can bring in all my operations at the base level or help me solve this error with any work arounds for my case.
This issue can be solved by passing an optional generic in the place of subBase class. I have attached the code for your reference. I have added the comments for the required area so that it would be helpful for someone in future
export abstract class Base<T extends BaseConstructor> {
protected prop1: T|undefined;
}
export class SubBase<B extends BaseConstructor> extends Base<SubConstructor | B> { // add optional generic here as the super class doesnt know which type to pass but the child class very well knows
constructor() {
super()
this.prop1 = new SubConstructor('Here')
}
}
export class BaseConstructor {
protected id!: number
}
export class SubConstructor extends BaseConstructor{
// some properties
subProp1: string = ''
constructor(subProp1: string) {
super()
this.subProp1 = subProp1
}
}
export class SubBaseChild extends SubBase<SubBaseChildConstructor> {
constructor() {
super()
}
}
export class SubBaseChildConstructor extends BaseConstructor {
subChildProp: number = 0
constructor(subChildProp: number) {
super()
this.subChildProp = subChildProp
}
}
Hope this would help you