When working with Typescript, an error is thrown if property "p" does not exist on one of the classes that are OR

In my component class, I have a property called renderContent which can be of either LessonPageType or TaskPageType based on the input value. Below is the code snippet from my component:

import {ChangeDetectionStrategy, Component, HostListener, Input, OnInit} from '@angular/core';
import {LessonPageType, TaskPageType} from '../../models/types';

@Component({
  selector: 'app-page-renderer',
  templateUrl: './page-renderer.component.html'
})
export class PageRendererComponent implements OnInit {

  @Input() renderContent: LessonPageType | TaskPageType;
  @Input() submission: TaskSubmissionType;
}

Issue: -

In my template, I'm trying to access the object within renderContent using renderContent?.accept_answer. However, the key accept_answer exists only in the TaskPageType and not in the other type. This discrepancy results in an error during AOT compilation as shown below. Is there any solution apart from changing the type of renderContent to any?

Error:-

ERROR in src/app/shared/components/page-renderer/page-renderer.component.html(16,17): : Property 'accepts_answer' does not exist on type 'LessonPageType | TaskPageType'. Property 'accepts_answer' does not exist on type 'LessonPageType'.

Answer ā„–1

When combining two or more interfaces/classes into a variable, only the properties that are common between them can be accessed. To address this limitation, I suggest the following solutions:

  • Add an optional accept_answer property to the LessonPageType
  • Extend the LessonPageType with TaskPageType to inherit all properties and add custom ones
  • As a last resort, define renderContent as type any

I hope these suggestions are helpful!

Answer ā„–2

Depending on the specific content you wish to display in your template with a LessonPageType, different approaches may be taken.

If the value is an empty string, one possible solution is as follows:

class PageRendererComponent implements OnInit {
  @Input() renderContent: LessonPageType | TaskPageType;
  @Input() submission: TaskSubmissionType;

  get acceptAnswer(): string {
    return 'accept_answer' in this.renderContent ? this.renderContent.accept_answer : '';
  }
}

Within your template, utilize the acceptAnswer function instead of directly accessing renderContent?.accept_answer.

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

Steps to simulate an injected service within a function using Injector

There is an implementation in Angular 7.x where a global error handling injects its services using the Injector. Each function has a reference with the injector, as shown below: import { ErrorHandler, Injectable, Injector, NgZone } from '@angular/co ...

Is there a way to turn off the warning overlay in a React application?

Iā€™m currently using react-app-rewired and I am trying to figure out how to turn off the overlay that displays Typescript warnings whenever I compile. It seems like some warnings that are not caught by the VSCode Typescript checker pop up on this overlay ...

Why aren't all client perspectives updated when I delete documents from the collection?

Currently, I am utilizing Angular2-meteor which is running on Angular2 Beta 1. Within my simple component, I have: A button to add a document. Once added, the document can be removed by its _id using another button. Additionally, there is a "Remove All" ...

Tips for relocating a switcher button using Ant Design Drawer in a React application

*I'm faced with a challenge in my React project where I need to synchronize the movement of a div (switcher-btn) and an Ant Design Drawer. Whenever the Drawer is opened, I want the switcher-btn to move along with it. Below is the code snippet I'v ...

The webpack-dev-server is missing the required module

Having trouble with starting my Angular project even after creating a new one using ng new AppName. When I run the project with ng serve, I still encounter an error that persists. Can someone help me resolve this issue? Error: Module not found - Error: Ca ...

Creating a gradient background with the makeStyles function

Why is it that the background: 'linear-gradient(to right, blue.200, blue.700)' doesn't work within makeStyles? I just want to add a gradient background to the entire area. Do you think <Container className={classes.root}> should be rep ...

My HTML files are not recognizing the IONIC Property within their own objects

As I delve deeper into understanding Angular and Ionic, a peculiar issue has arisen for which I seek a solution. I have several export classes containing HTML forms. In each corresponding .ts file, I declare a variable and import the relevant model to bin ...

Maintain query parameters in Angular6 while routing with canActivate

When using Auth guard to verify login status and redirecting to the login page if a user is not logged in, there seems to be an issue with losing all query parameters during the redirection process. I attempted to preserve the query params by adding { qu ...

Generate a unique Object URL for the video source by utilizing the binary string obtained from the backend

I've been facing an issue with loading binary video data from my backend using fastAPI. When I curl the endpoint and save the file, it plays perfectly fine on my laptop. For the frontend, I'm using React+Typescript. I fetch the binary video data ...

classes_1.Individual is not a callable

I am facing some difficulties with imports and exports in my self-made TypeScript project. Within the "classes" folder, I have individual files for each class that export them. To simplify usage in code, I created an "index.ts" file that imports all class ...

Tips for incorporating user access control logic into a lazy-loaded Angular Monorepo application without embedding the logic in the main application

In our current project, we are developing an Angular application utilizing the Angular monorepo structure. This setup includes a parent application and several children applications, with the parent application located in the `app` folder and the children ...

What is the best way to store a logged-in user's email in a React

I have implemented a login API and I would like to save the email of the logged-in user in the state or another variable, so that I can display it in the header after successful login. The user's email is located in the data.email. The following code ...

What is the best way to determine the remaining time until a cookie expires in seconds?

I recently set a cookie with an expiration time of 2 minutes. Now, I am looking for a way to display a countdown in HTML showing the seconds remaining before that specific cookie expires using Angular 2. ...

Embracing Angular 9 Ivy results in encountering errors

After updating my app to Angular 9, I encountered an issue with Ivy where I receive the error error NG6002: The error logs are as follows - 32 export class FooterModule { } ~~~~~~~~~~~~ src/app/core/ncpapp.core.module.ts:30:14 - error NG6002: ...

Error: Unable to parse string in URI within vscode API

Console LOG displays: \Users\skhan\Library\Application Support\Code\User\summary.txt The loop is used to replace the slashes. It works fine in Windows but not in Ubuntu and Mac. This is an example on OSX 10.11.6. Howev ...

Encountering an Uncaught TypeError when attempting to set properties of null with useRef

I've been working on an app that requires access to the user's device camera in order to display live video on the screen. I've managed to achieve this by utilizing a video HTML Object and setting the media stream as its srcObject. Everythin ...

Choosing Angular.json setups while executing a Docker multi-stage construction

I am currently in the process of developing an Angular6 application with a Docker multistage build. The default angular.json file generated by angular.cli includes a build section containing various configurations. To choose a specific configuration, I can ...

Dealing with Errors in Angular 2/4 using forkJoin for Multiple URLs

I am currently using Angular 2 and implementing forkJoin for a particular scenario where I need to make multiple REST calls in parallel. Below is the function I am using: private getBatchObservableData(data: Array<Widget>): Observable<any> { ...

Tips for obtaining the rotation angle within the Ionic gesture API?

Currently, I am working on canvas and facing an issue while handling gesture events with Hammer.js. Despite seeking help in various forums, including this one, I have yet to receive a response. Now, I am trying my luck with Ionic gestures but struggling to ...

Top method for changing Enum to Set in TypeScript

Take a look at the enum below: enum Animes { OnePiece = 'One Piece', Naruto = 'Naruto', Bleach = 'Bleach' } How can we efficiently transform this enum into a Set? ...