I'm creating a parent and child class in Typescript. Each one defines some fields (properties). I'm trying to keep the code clean, using the Partial<T> method for the constructors. But I'm not sure how to pass the parent's properties to the parent in the super() call and initialize the child's props with only the child's unique props in Object.assign() -- if that's even the right paradigm. Here's what I have:
export class Parent {
name: string = ''
durationInSec: number = 0.0
optionalField?: string;
constructor(init: Partial<Parent>) {
Object.assign(this, init)
}
}
export enum Types { A, B, C }
export class ChildA extends Parent {
kind = Types.A
childRequired1: string = '' // ??? have to set defaults for all props with this technique
childOption1?: string
constructor(init: Partial<ChildA>) {
super(init) // ??? wrong, passes too many things to super
Object.assign(this, init) // this would be fine alone, but tsc says need to call super()
}
}
// similar for ChildB, ChildC etc.
let obj1 = new ChildA({name: 'foo', childRequired1: 'bar'})
Is this even a good paradigm in Typescript? Is there a better way?
??? have to set defaults for all props with this technique" ... what's the alternative? If you have required props you need to set defaults somewhere, right? Or am I missing something? Also, why not callsuper({})in the subclass and then do yourObject.assign(this, init)afterward?Partial<T>, so they're not really required.