Looking at the code snippet below, my aim is to ensure that all classes which implement InterfaceParent
must have a method called add
that takes an instance of either InterfaceParent
or its implementing class as input and returns an instance of InterfaceParent
or its implementing class. However, due to the fact that InterfaceChild
introduces a new field called randomVariable
which is not part of the interface it implements, I encounter the following error message:
Property 'add' in type 'InterfaceChild' is not assignable to the same property in base type 'InterfaceParent'.
Type '(n: InterfaceChild) => InterfaceChild' is not assignable to type '(n: InterfaceParent) => InterfaceParent'.
Types of parameters 'n' and 'n' are incompatible.
Property 'randomVariable' is missing in type 'InterfaceParent' but required in type 'InterfaceChild'.ts(2416)
InterfaceParentChild.ts(6, 3): 'randomVariable' is declared here.
What seems to be the issue? Here is the code I am currently working with:
interface InterfaceParent {
add: (n: InterfaceParent) => InterfaceParent
}
class InterfaceChild implements InterfaceParent {
randomVariable: number = 1
add = (n: InterfaceChild): InterfaceChild => new InterfaceChild()
}
export default InterfaceChild