I’m using TypeScript and I have the following scenario.
Let’s say I have a base type and some derived types, something like this:
export interface Base {
id: string;
}
export interface A extends Base {
propA: string;
}
export interface B extends Base {
propB: string;
}
And let’s say I also have an array of the base type:
let items: Base[];
Now, here’s my problem: I want to initialize that array with some objects, and I though I could just do this:
items = [
{id: "1", propA: "foo"},
{id: "2", propB: "bar"}
];
However, this doesn’t work, I get an error from the compiler saying that:
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’.
But the objects I declared are indeed instances of Base, and in fact if I do something like:
const objA: A = {id: "1", propA: "foo"};
items.push(objA);
the compiler doesn’t complain.
So, is it possible to do this inline object declaration, or am I forced to declare all objects separately and manually pushing them onto the array?
>Solution :
You can do either
items = [
{ id: "1", propA: "foo" } as A,
{ id: "2", propB: "bar" } as B
];
or
let items: Array<A | B>;