I'm fairly new to Typescript and currently grappling with how to effectively manage class inheritance when base classes have distinct properties.
Essentially, I have a base class where I aim to define shared functionality and a series of subclasses with varying properties that correspond to different database models. I'm trying to determine the best approach for defining the types in this scenario.
For instance:
class BaseClass {
static create(props) { /*... */ }
update(props) { /*... */ }
}
type SubClassOneProps = {
firstName: string
lastName: string
}
class SubClassOne extends BaseClass {
firstName!: string
lastName!: string
}
type SubClassTwoProps = {
streetName: string
streetNumber: number
}
class SubClassTwo extends BaseClass {
streetName!: string
streetNumber!: number
}
// I want to establish typings that facilitate the following:
SubClassOne.create({firstName: "Bob", lastName: "Doe"})
SubClassTwo.create({streetName: "Sunset Blvd", streetNumber: 100})
// and apply a similar concept to the instance methods, though I may utilize Partial<> for these
Due to the unique properties in each subclass, the signatures vary slightly, even though they all consist of basic key/value pairs. I'm struggling to determine the correct typing and how to specify the properties for each subclass.
In addition, I'll need to include some metadata for each property (specifically, whether they are publicly accessible), and create an instance method that can output the public properties to a JSON object. However, I'll tackle that issue separately at a later time.
Any advice or guidance on this matter would be greatly appreciated!