Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Specifying type of inline object in TypeScript

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading