As a newcomer to typescript, imagine having the following scenario:
class Foo{
options: fooOptionsObj;
constructor(options: fooOptionsObj){
this.options = options;
}
sayMessage(){
console.log(`I am number${this.options.position}, and I say ${this.options.message}`);
}
}
interface fooOptionsObj{
message: string;
position: number;
}
You can create a subclass of Foo
, and utilize fooOptionsObj
to provide the options
class SubFoo extends Foo{
subOptions: subFooOptionsObj;
constructor(superOptions: fooOptionsObj, subOptions: subFooOptionsObj){
super(superOptions);
this.subOptions = subOptions;
}
draw(){
drawSqaure(0, 0, this.subOptions.size, this.subOptions.size, this.subOptions.color);//assume this is a function
}
}
interface subFooOptionsObj{
color:string;
size:number
}
If you wanted to create another one:
class DifferentSubFoo extends Foo{
...
}
You would have to pass different arguments into the superclass than in the subclass, leading to potential confusion.
The ideal solution would be to use only one argument, an options
object, typed as whateverClassYourUsingOptionsObj. For instance:
class ThreeLetters{
options: fooOptionsObj|barOptionsObj;
constructor(options: fooOptionsObj|barOptionsObj){
this.options = options;
}
sayMessage(){
console.log(this.options.message)
}
}
class Foo extends ThreeLetters{
constructor(options: fooOptionsObj){
super(options)
}
returnBol(): boolean{
return this.options.bool;
}
}
class Bar extends ThreeLetters{
constructor(options: barOptionsObj){
super(options);
}
sayNumber(){
console.log(this.options.num);
}
}
interface fooOptionsObj{
message: string;
bool: boolean;
}
interface barOptionsObj{
message: string;
num: number;
}
However, there's a catch - because barOptionsObj
lacks a bool
, and fooOptionsObj
lacks a num
, even though they should not require both. This dilemma arises from the fact that within ThreeLetters
, the options
type is barOptionsObj|fooOptionsObj
, despite the fact that it will be exclusively one or the other (per instance). How could I solve this issue, so that only one options
object is necessary?