Похоже, вы хотите определить интерфейсы вместо классов здесь.Как насчет:
interface CommonInterface {
coreProp: string
}
interface InterfaceA extends CommonInterface {
classAProp: string
};
interface InterfaceB extends CommonInterface {
classBProp: number
};
type CoreInterface = InterfaceA | InterfaceB;
const testStringProp: CoreInterface = { coreProp: 'test', classAProp: "testString" };
const testNumberProp: CoreInterface = { coreProp: 'test', classBProp: 43 };
const testError: CoreInterface = { coreProp: 'test' };
//error: needs either classAProp or classBProp
Реализация интерфейсов путем создания новых объектов:
class CommonClass {
coreProp: string
// ...
}
class ClassA extends CommonClass {
classAProp: string;
constructor(props: InterfaceA) {
super();
this.coreProp = props.coreProp;
this.classAProp = props.classAProp;
}
};
class ClassB extends CommonClass {
classBProp: number;
constructor(props: InterfaceB) {
super();
this.coreProp = props.coreProp;
this.classBProp = props.classBProp;
}
};
class ClassAorB extends CommonClass {
classAProp: string;
classBProp: number;
constructor(props: CoreInterface) {
super();
this.coreProp = props.coreProp;
const propsA = props as InterfaceA;
const propsB = props as InterfaceB;
if (propsA.classAProp) {
this.classAProp = propsA.classAProp
}
if (propsB.classBProp) {
this.classBProp = propsB.classBProp
}
}
};
const objOfClassA = new ClassA({ coreProp: 'test', classAProp: 'testString' });
const objOfClassB = new ClassB({ coreProp: 'test', classBProp: 43 });
const objA = new ClassAorB({ coreProp: 'test', classAProp: 'testing' });
const objB = new ClassAorB({ coreProp: 'test', classBProp: 43 });
const testError = new ClassB({coreProp: 'test'});
//error: needs classBProp
const testAntotherErr = new ClassAorB({coreProp: 'test'})
//error: needs either classAProp or classBProp