In an Angular application, I am using a base interface with some common properties and two child interfaces extending it:
interface BaseConfig {
id: number;
name: string;
type: ConfigType
}
interface UserConfig extends BaseConfig {
socialNr: number;
}
interface OrderConfig extends BaseConfig {
shipDate: Date;
}
enum ConfigType {
User: 'user',
Order: 'order'
}
The goal is to leverage polymorphism and use the base class as type for both child interfaces, for example:
export interface State extends EntityState<BaseConfig> {
loaded: boolean;
selectedBookConfig: BaseConfig | null; // This can be either UserConfig or OrderConfig
}
On the component side I can check the type and cast accordingly:
if (this.config?.type == ConfigType.User) {
this.view = (this.config as UserConfig).socialNr;
}
The problem is however in the templates, where I get errors for the child properties, missing in the base interface. In the following snippet, I would refer to the case of an UserConfig:
// config has the base type: `BaseConfig`
<div [ngSwitch]="config.type">
<span [ngSwitch]="ConfigType.User"> {{ config.socialNr }} </span>
</div>
The error is: Property 'socialNr' does not exist on type 'BaseConfig'.
How could I use a base interface as root/generic type for its extending interfaces/types without incurring in the template issues as above?
UserConfigandOrderConfigdoesn't extendsBaseConfig, is that normal ?UserConfigthe type of the object ? else, with a cast likemyObj as UserConfig?