In my use of TypeScript
, I encounter the following situation.
Imagine I have a base type and several derived types, structured as follows:
export interface Base {
id: string;
}
export interface A extends Base {
propA: string;
}
export interface B extends Base {
propB: string;
}
Furthermore, let's say I have an array of items with a base type:
let items: Base[];
Now, here lies my issue: I aim to initialize this array with specific objects directly, like so:
items = [
{id: "1", propA: "foo"},
{id: "2", propB: "bar"}
];
However, attempting this approach triggers an error from the compiler stating:
TS2322: Type '{ id: string; propA: string; }' is not assignable to type 'Base'. Object literal may only specify known properties, and 'propA' does not exist in type 'Base'.
Even though the declared objects are instances of Base
, if I explicitly define them first like:
const objA: A = {id: "1", propA: "foo"};
items.push(objA);
then the compiler does not raise any issues.
Therefore, my question is whether it is feasible to declare these objects inline or if I must separately define and push them onto the array manually?