Currently, I am working on incorporating typings into a library that heavily utilizes inheritance. The hierarchy typically follows this structure:
BaseWidget --> TextBox --> ValidationTextBox
In the BaseWidget class, there is a JavaScript function called getObj(name)
, which translates to getObj(name: string): any
in TypeScript. This function essentially searches for a method named _get<name>
within the current object, executes it, and returns the result.
These 'properties' are exposed in the individual classes and inherited across classes, allowing ValidationTextBox to access all the properties present in TextBox. My question revolves around whether it is possible to add typings similar to my attempt below without having to redefine the overloads in each class.
interface BaseWidget {
getObj(name: string): any
}
interface TextBox extends BaseWidget {
getObj(name: "B"): string
}
interface ValidationTextBox extends TextBox {
getObj(name: "C"): boolean
// getObj(name: "B"): string; // Adding this line would make it compile, but it's not the best solution.
// getObj(name: string): any // Adding this also compiles, but it results in losing type information for 'getObj("B")'
}
declare const obj: ValidationTextBox;
console.log(obj.getObj("B")); // Error: Argument of type '"B"' is not assignable to parameter of type '"C"'
The current issue with this approach is the error message stating
Interface 'ValidationTextBox' incorrectly extends interface 'TextBox'
, due to the fact that "B" cannot be assigned to "C" in the context of getObj(...)
.
I appreciate any assistance provided!