Working with ES6 classes and TypeScript to create a user interface, I have a base class named Control
. I am looking for a way to create a Button, which is essentially an instance of Control
with predefined properties. To achieve this, I have used Button
as a sub-class of Control
.
As I delved deeper into this implementation, I realized that my sub-class simply calls super() with the control type
set to 'button'. Additionally, Button enforces certain control properties to be mandatory, leading me to question the correctness of this approach. Is using a sub-class the ideal OOP solution for this scenario? What would be a more effective way to tackle this problem?
interface ControlOptions {
type: string;
label?: string;
onClick?: () => void; // optional here
submit?: boolean;
transition?: Transition
}
class Control {
constructor(options: ControlOptions) {
}
// Some methods left out for brevity.
}
interface ButtonOptions {
label: string
onClick: () => any // mandatory here
submit?: boolean
transition?: Transition
}
// Is subclassing the right choice here?
class Button extends Control {
constructor(options: ButtonOptions) {
let controlProps = { type: 'button', ...options };
super(controlProps);
if (options.transition) {
options.transition.setSource(this);
}
}
}