Setting up some type script classes and just wondering if there is a better way to structure the Partial constructor to accommodate for a couple of different input types.
In principle I want the TextBlock class to always output TextModel and a RichText or null. But for the constructor to take either a string, RichText or null. If the user passes a string into the constructor for it to convert it to a RichText via its constructor.
The best way I have found to deal with this is to create an interface that for this input can have any of the 3 types, but the class to only have the 2 types. This keeps the output type safe but allows me to pass multiple types into the constructor.
interface TextBlockModel
{
textModel : RichText | string | null;
}
export class TextBlock
{
textModel: RichText | null = null;
constructor(source? : Partial<TextBlockModel> | null)
{
Object.assign(this, source);
this.textModel = new RichText(source?.textModel);
console.log("textblock", source)
}
}
There may not be a nicer way to do this, but just wondering if there is. I have striped the code down to highlight the questions use case. If it was just this 1 variable would not use the partial constructor.