Within my coding framework, I have developed the following interface within an abstract base class:
interface MyInterface {
field1: string
}
abstract class BaseClass {
// some fields here...
abstract serialize(): Array<MyInterface>
}
As I progress, I find myself creating multiple subclasses that inherit from BaseClass
, each with unique additional fields. For example:
class Subclass1 extends BaseClass {
// some additional fields that are not in BaseClass
serialize(): Array<MyInterface> {
return [{field1: "test", field2: "test2"}];
}
}
At this point, I am seeking the appropriate return type for the serialize
function, which should adhere to the idea of:
"return any object that implements MyInterface, including all fields required by MyInterface and possibly more"
While reviewing this setup, I encounter an error in Typescript due to the return type failing to comply with MyInterface
. This is logical, as field2
is not part of the interface.
In essence, I believe I require something akin to a Java unbounded wildcard in Typescript, such as:
List<? extends MyInterface>
This signifies any object implementing MyInterface
.