Determining the data type of an inline object in TypeScript

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?

Answer №1

There are two options available:

items = [
    { id: "1", propA: "foo" } as A,
    { id: "2", propB: "bar" } as B
];

You can choose to either use the array defined above or define it like this:

let items: Array<A | B>;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can one determine if a background image has successfully loaded in an Angular application?

In my Angular 7 application, I am displaying a background image in a div. However, there are instances when the link to the image is broken. The way I bind the image in my HTML is as follows: <div [ngStyle]="{'background-image': 'url(&a ...

Typescript error encountered in customized PipeLine class

I am currently developing a web scraping application using Puppeteer. In this project, I aim to create a PipeLine class that will take the current instance of the page and expose an add method. This add method should accept an array of functions with the t ...

Creating services in Angular is a continuous process

How can I create a service as singleton in Angular? I have a service that is injected into 2 components and the value is set to true. However, every time I open the view, the service is created again and the value resets to false. How can I make sure the ...

Troubleshooting a TypeScript and Node.js FileSystem problem

I recently encountered a strange issue with my simple TypeScript program. /// <reference path="node-definitions/node.d.ts" /> import fs = require('fs'); fs.writeFileSync("test.txt","HelloWorld"); When I try to run it, the console outputs ...

Can you explain the meaning behind the exclamation mark in Angular syntax?

I've noticed this popping up in a few spots lately, but I haven't been able to find any information about it. I'm intrigued by the use of the '!' symbol in Angular syntax. Can anyone explain what it does? https://i.sstatic.net/sj ...

angular2 *ngIf fails to render content when condition is true and array is empty

Here's the code I'm working with: This is the templateUrl: <button class="btn btn-success" (click)="showNewPop()" >New</button>{{shownew}} <app-new-pop *ngIf="shownew" (close)="closeNewPop($event)"></app-new-pop> And h ...

What is the process in Ionic 3 for invoking a method housed within a tab class?

I'm currently developing an Ionic app that features a "home" page with 3 tabs. My goal is to implement a search bar for these tabs by triggering a method inside the selected tab's class whenever the search term changes. Below is the structure of ...

Issue with font-size changes using css variables in Angular not updating in browser for specific fields

Utilizing CSS variables, I have implemented a feature that allows users to adjust the font size to small, medium, or large. While this functionality works correctly for most fields, there are certain instances where the value is applied but not displayed. ...

Encountering an issue with d3 Angular 2 pie chart related to d3.arc data

I encountered a problem with my code: 'PieArcDatum' is not assignable to parameter of type 'DefaultArcObject.' at this specific line Argument of type return "translate(" + labelArc.centroid(d) + ")";. Could someone please assist me in ...

Steps to Refresh the URL in an Angular 2 Application

I'm facing an issue with this in Angular 2. When I refresh the URL, I need to wait for the page to finish loading before performing a certain action. However, I haven't been able to figure it out successfully: fetchLoginPage() { return this.ht ...

What is the best way to access an external website from your code

I am currently working on an application using Angular 6, and I have encountered a scenario with two URLs. The first URL (url 1) is , while the second URL (url 2) is . In this setup, users who are logged in via url 1 should only be able to redirect to ur ...

Slim API receives a request from Ionic 5

Seeking assistance with making a GET request from my Ionic application to an API constructed using the Slim Framework. Below is the code snippet of the API: <?php header('Access-Control-Allow-Origin: *'); header('Content-Type: applicati ...

Encountering an issue while trying to load a file from an API due to difficulties in parsing it to

When trying to load an xlsx file from an API, I encountered an error because Angular automatically tries to parse the body as JSON. To resolve this issue, I found that specifying the response type directly in the request works: this.http.get(this.url + " ...

Accessing and modifying the properties of Component a from Component b

I have developed two components that are both utilizing the same Service I created. #Component A @Component({ templateUrl: 'build/pages/templateReunionCourse/templateReunionCourse.html', providers: [ ReunionService,JS ...

A comprehensive guide on enabling visibility of a variable within the confines of a function scope

In the code snippet shown below, I am facing an issue with accessing the variable AoC in the scope of the function VectorTileLayer. The variable is declared but not defined within that scope. How can I access the variable AoC within the scope of VectorTile ...

Comparing Static Factory Methods and Constructors

This question led to an interesting discussion in the comments, focusing on the advantages of Static Factory Methods versus Constructors. Consider the following example: export class User extends Model<UserProps> { // Recommended Method (Without ...

Protractor is the ultimate way to verify the visibility of an element

Does anyone have a good method for checking if an element is visible using Protractor? Here's what I've tried: element.isPresent().then(result=>{ expect(result).toBeFalsy(); }); This works well, but I want to specifically check if the ...

The Enum object in TypeScript has not been declared or defined

For my TypeScript application, I am utilizing WebPack to transpile and bundle the code. The final result is intended to be used in a pure JavaScript website. One of the components in my application is an enum defined as follows: export const enum ShapeTyp ...

Error TS2345: The type '{ type: "mouseWheel"; }' cannot be assigned to the parameter of type 'MouseInputEvent | MouseWheelInputEvent | KeyboardInputEvent'

I've integrated the sendInputEvent method into BrowserView: view.webContents.sendInputEvent({type: 'keyDown', keyCode: 'C'}) In the rendering page of BrowserWindow, I've added: window.addEventListener('keydown', ...

Performing a test on API GET Request with Playwright

I've been attempting to verify the GET status using this particular piece of code. Regrettably, I keep encountering an error message stating "apiRequestContext.get: connect ECONNREFUSED ::1:8080". If anyone has any insights or suggestions on how to re ...