Issue TS1112: It is not possible to declare a class member as optional

I'm currently working on creating a movie catalog using Angular and Ionic. Within the Movie class, I have properties for id, title, image, and plot.

On the initial page of the app, only the id, title, and image are displayed, while the plot is omitted.

Movie Class

export class Movie{
    id: number;
    title: string;
    img: string;
    plot?: string;
}

Within the main typescript file, I am populating the movie details in the following manner:

export class MainPage implements OnInit{

    movies: Movie[];
    getMovies(){
        this.movies = [{id: 1, title: 'test', img: 'img1'}]
    }
    ngOnInit(){
        this.getMovies();
    }
}

However, this results in the following error:

Error TS1112: A class member cannot be declared optional. The issue lies with the 'plot' variable.

Is there a way to achieve my intended goal? Are there any alternative solutions?

Thank you in advance for your assistance!

Answer №1

If you have a Movie class that is only defining a data structure without any implementation code, consider changing it to an Interface:

interface Movie{
    id: number;
    title: string;
    img: string;
    plot?: string;
}

Alternatively, if the class needs to include the plot property without the optional operator, make sure to set plot to null in the getMovies method:

class Movie{
    id: number;
    title: string;
    img: string;
    plot: string;
}

class MainPage {

    movies: Movie[];
    getMovies(){
        this.movies = [{id: 1, title: 'test', img: 'img1', plot: null}]
    }
    ngOnInit(){
        this.getMovies();
    }
}

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 to extract the root website URL using JavaScript for redirection purposes

I am facing an issue with redirecting to the Login page from every page on my website after session timeout. I attempted to set the window location to the login page using the following code: var ParentUrl = encodeURIComponent(window.parent.location.href) ...

Concealing a div depending on the price variation

I'm looking for a way to dynamically show or hide a div based on the price of selected variations in my online store. Let's take a product with options priced at £359 and £455 as an example. In addition, there is a finance plugin with a minim ...

The issue with ng-change is causing the previously selected drop down option to be cleared

After successfully implementing live searching with ng-change, I encountered an issue with a pre-selected drop-down box. Despite setting the selected="selected" attribute to make option three the default selection, the drop-down box jumps to the top optio ...

Unable to prolong TypeScript document

As I develop a drag and drop interface, upon dropping a file, the native File is retrieved. To enhance this interface with additional information, I decided to explore various approaches. In my initial attempt, I utilized: interface AcceptedFile extends ...

Issue with pre-selected default value in AngularJS TypeScript Kendo UI DropDownList

I have successfully implemented a list of objects for items, but now I am facing a challenge in adding a default selected value. Below is the HTML code for the drop-down: <select kendo-drop-down-list k-options="selectItems" k-ng-mode ...

Is indexed coloring available for vertices in three.js?

I have recently started exploring the world of three.js and I am aware that there is a way to color vertices in three.js. However, I am currently researching whether it is possible to implement indexed colors for vertices in three.js or WebGL. Specifically ...

Sending an object between two components without a direct parent-child connection

Hello, I have a question similar to the one asked on Stack Overflow regarding passing a value from one Angular 2 component to another without a parent-child relationship. In my scenario, Component1 subscribes to a service that makes a GET request to the ...

What could cause a member variable to be uninitialized in the ngInit method in Ionic/Angular, even though it was initially set in the constructor

Despite setting the modal form to be bound to an instance of "Foo" during its construction, I encountered a strange issue where, post-constructor, this.foo became undefined. Even after verifying this through breakpoints and console.log, the problem persist ...

Can you explain the use of parentheses in a typescript type when defining a key?

Could someone provide an instance of an object that matches the TypeScript type below? I'm a bit confused because I've only worked with interfaces before and have only seen square brackets. type Hash = { (data: Uint8Array): Uint8Array blockLe ...

How can I retrieve a certain type of object property in TypeScript?

Imagine having a collection of flags stored in an object like the example below: type Flags = { flag1: string, flag2: string, flag3: boolean, flag4: number } // const myFlags: Flags = { // flag1: 'value 1', // flag2: 'value 1&ap ...

Is it possible to use Javascript to gradually fade in text, one word at a time, with multiple divs instead of just one?

I am attempting to gradually fade in individual words from a div. While the code below works fine for a single div, it does not execute sequentially when multiple divs are involved. Here is the fiddle : http://jsfiddle.net/zlud/6czap/110/ Can anyone spot ...

Executing a single insert statement in a TypeScript Express application using PostgreSQL is taking over 240 milliseconds to complete

Seeking assistance with optimizing a db insert operation test using mocha for a node.js express app that utilizes fp-ts and pg npm package. The tests run successfully, but the insert test is taking over 240 ms to complete. The database table has a maximum ...

Ways to incorporate a dynamic HTML form that allows for input elements to be added both horizontally and vertically while maintaining connected lines

Looking to design a form that showcases HTML elements in both vertical and horizontal positions, with lines connecting them as seen in this example: https://i.sstatic.net/jB12f.png. Can anyone offer guidance on how to achieve this? Thanks! ...

Cloudflare SSL Error 522 Express: Troubleshooting Tips for Res

After setting up my express project using express-generator, I decided to make it work with a cloudflare SSL Certificate for secure browsing over https. My express app is running on port 443. Despite my efforts, when I try to access the domain, I encount ...

jQuery's outerHeight() and height functions may experience flickering or fail to update properly when the window is resized to an odd number

Two elements are placed side by side on a webpage. One element, with a fixed size of 100vh, is named .hero-half, while the other element, holding text of varying lengths, is fluid and labeled as .project-details. When the text container extends beyond the ...

The display of options in React Bootstrap typeahead is not functioning properly

When I try to implement React Bootstrap Typeahead, the options do not appear in the Typeahead component upon page load. Here is a snippet of my code: const React = require('react'); ... (code continues) The options are generated as follows: [ ...

Using Angular's ng-show directive, create a custom Kendo Listview template to toggle the display of an

Currently, I am working with a Kendo Listview to display charts and would like to implement a feature where users can click on a checkbox to show or hide individual charts. Despite my efforts to use ng-show, I have been unsuccessful in making it work. Bel ...

Steer clear of performing DOM manipulation with jQuery within an ng-repeat directive

As a beginner in Angular, I am currently developing a simple CRUD application. I have learned that it is recommended to avoid using jQuery for DOM manipulation whenever possible. Currently, I am faced with the challenge of removing a row from the DOM when ...

Angular compodoc tool is not considering *.d.ts files

Is there a way to make compodoc include .d.ts files in the documentation generation process for my Angular project? Even though I've added all .d.ts files to tsconfig.compodoc.json as shown below: { "include": [ "src/**/*.d. ...

What is the best way to connect information from an HTML input field to a JavaScript object with the help of AngularJS?

As a beginner in AngularJS, I'm struggling to find the best approach to achieve my goal. I aim to create a grid of input tags with type=number in my HTML and have it set up so that whenever the value is increased, a new object is added to a list. Simi ...