Exploring Class Inheritance and TypeScript Errors
class A {
prop: string
}
when extending the parent class:
class B extends A {
prop?: string
}
A Challenge Arises:
TypeScript error message:
Property 'prop' in type 'B' is not assignable to the same property in base type 'A'.
Type 'number | undefined' is not assignable to type 'number'.
Type 'undefined' is not assignable to type 'number'.ts(2416)
Solution Attempt:
Creating a function for optional properties inheritance:</p>
<code>function OptionalizeParent<T>(cls: T): Partial<T>{
return cls
}
Implementation in the child class:
class B extends OptionalizeParent(A) {
prop?: string
}
New Error Imposed:
Error - 'Partial<typeof A>' is not a constructor function type.
Considering Workarounds:
Moving away from Liskov substitution principle, focusing on solution.
Note: TypeScript provides MapConstructor
interface that may be relevant.