I have a base interface that defines an object type in my code and multiple other interfaces that extends it. This base interface will be an attribute for a base class and then the derived class will have the extended interface as attributes. How can I use the extended interfaces in the derived class without always using the as
keyword in typescript ?
interface BaseData {
id: string;
}
interface DerivedDataA extends BaseData {
derivedFieldA: number;
}
interface DerivedDataB extends BaseData {
derivedFieldB: boolean;
}
class BaseClass {
data: BaseData;
constructor(data: BaseData) {
this.data = data;
}
getId() {
console.log(this.data.id);
}
compute() {
// implement in derived class
}
}
class DerivedClassA extends BaseClass {
compute() {
// This is the issue I am having, how to use the derived interface without `as`
console.log((this.data as DerivedDataA).derivedFieldA);
}
}
class DerivedClassB extends BaseClass {
compute() {
// This is the issue I am having, how to use the derived interface without `as`
console.log((this.data as DerivedDataB).derivedFieldB);
}
}
I have tried using generic types but it doesn't seem to fit as a solution. How would one do this in another language other than typescript? Also is this an anti-pattern/bad practice? Thanks