How can I retrieve properties from a superclass in Typescript/Phaser?

Within my parent class, I have inherited from Phaser.GameObjects.Container. This parent class contains a property called InformationPanel which is of a custom class. The container also has multiple children of type Container.

I am attempting to access the informationPanel in the main container from a child that is located two levels down using the following code:

this.parentContainer.parentContainer.informationPanel.setText(text)

The structure can be visualized as follows: Shop --> button container --> button.

While the code works, it generates an error message:

Property 'informationPanel' does not exist on type 'Container'

Although the functionality is intact, the presence of these error indicators is bothersome. I'm curious if there's a way to eliminate them.

export default class ShopContainer extends Phaser.GameObjects.Container {

    private upgrades!: UpgradeContainer
    
    constructor(scene: Phaser.Scene, x: number, y: number, width: number, height: number, playerMoney: MoneyLabel) {
        super(scene, x, y)

        this.upgrades = new UpgradeContainer(scene, width / 2, 100)
}
export class UpgradeContainer extends Phaser.GameObjects.Container {
    private _buttons!: Array<UpgradeButton>
    .
    .
    .
    public createButton(texture: string, description: string, func: string, label: string, price: number, priceMultiplier: number) {
        let X_OFFSET = 0
        let Y_OFFSET = 0
        const index = this._buttons.length

        if (this.isLandscape) {
            const y_off = 58
            const row = this._buttons.length
            Y_OFFSET = row * y_off
        } else {
            const x_off = 200
            X_OFFSET = -200 + index * x_off
        }

        const button = new UpgradeButton(
            this.scene,
            X_OFFSET,
            Y_OFFSET,
            texture,
            description,
            () => {
                // 1. Subtract money
                this.eventDispatcher.emit('add-money', -button.getPrice())

                // 2. Increase price
                button.increasePrice()

                // 3. Emit upgrade
                this.eventDispatcher.emit(func)
            },
            label,
            price,
            priceMultiplier,
            index
        )

        this._buttons.push(button)
        this.add(button)
}
/**
 * Creates a Upgrade Button that, in addition to the Button functionality, 
 * controls the upgrades availability
 */
export default class UpgradeButton extends Button {
    .
    .
    .
}
export default class Button extends Phaser.GameObjects.Container {

    private func: Function
    private buttonImage: Phaser.GameObjects.Image
    private label: string
    private description: string
    private cost: number

    constructor(scene: Phaser.Scene, x: number, y: number, buttonTexture: string, label: string, description: string, cost:number, event: Function) {
        super(scene, x, y)

        this.func = event
        this.label = label
        this.description = description
        this.cost = cost

        // Create the image
        this.buttonImage = scene.add.image(0, 0, buttonTexture)
            .setOrigin(0.5)
        // Add image to container
        this.add(this.buttonImage)

        // Add the information panel
        this.setSize(this.buttonImage.width, this.buttonImage.height)

        // Add interactive actions
        this.makeInteractive()
    }
    
    useHoverState() {
        this.buttonImage.setTint(EColor.Buttons.Basic.HOVER)
        this.parentContainer.parentContainer.informationPanel.setLabel(this.label) // This is where the error squiggles appear (on .informationPanel)
        this.parentContainer.parentContainer.informationPanel.setDescription(this.description)
        this.parentContainer.parentContainer.informationPanel.setCost(this.cost)
        this.parentContainer.parentContainer.informationPanel.setVisible(true)
    }

Answer №1

It's a bit unclear to me what your code/question is about, but if you want to remove the squiggles, you can try the following approaches:

Convert the object into your custom class: InformationPanel

    let panel = this.parentContainer.parentContainer.informationPanel as InformationPanel;
    panel.setLabel(this.label);
    panel.setDescription(this.description);
    panel.setCost(this.cost);
    panel.setVisible(true);

Alternatively, you could do it like this:

let panel = <InformationPanel> this.parentContainer.parentContainer.informationPanel ;

For more detailed information on type casting, check out this link:

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

Encountering "Undefined error" while using @ViewChildren in Angular Typescript

In my application, I am facing an issue with a mat-table that displays data related to Groups. The table fetches more than 50 rows of group information from a data source, but initially only loads the first 14 rows until the user starts scrolling down. Alo ...

Implementing setInterval() leads to the dynamic alteration of images

I've created Marquees using CSS animations and a countdown timer. The Marquees display 100 random images that move from left to right and right to left. However, when the countdown timer decreases, the images in the Marquee change but the scrolling co ...

The strict mode in React reveals unexpected changes in state with double rendering

While working with React, I've noticed that it renders twice in Strict mode during development to ensure the function remains pure without any side effects. However, I'm facing some inconsistency in retrieving the state in my case. It seems like ...

Error encountered in ngtsc(2345) where an argument of type 'Event' is being used instead of an expected parameter type of 'SortEvent'

I recently started using angular and encountered an issue while trying to sort columns. The error message I received was: Argument of type 'Event' is not assignable to parameter of type 'SortEvent'. Type 'Event' is missing t ...

How can I transfer a collection of JSON objects from JavaScript to C#?

Feeling a bit confused here. I have some Javascript code that will generate JSON data like the following: {type:"book" , author: "Lian", Publisher: "ABC"} {type:"Newspaper", author: "Noke"} This is just one example, I actually have more data than thi ...

TSConfig - Automatically Generates a ".js" File for Every ".ts" File

Having a unique software application with an unconventional file structure project ├── tsconfig.json ├── app_1 │ ├── ts │ └── js | └── app_2 ├── ts └── js I aim to compile files located inside the ...

How can I personalize the color of a Material UI button?

Having trouble changing button colors in Material UI (v1). Is there a way to adjust the theme to mimic Bootstrap, allowing me to simply use "btn-danger" for red, "btn-success" for green...? I attempted using a custom className, but it's not function ...

Have you considered retrieving POST parameters using Ajax POST in jQuery?

Below is the code snippet: $.ajax({ type: "POST", url: "http://localhost:3000/rcm/global_config/update", data: {k: 'sdfa', v: 'dsfas'}, success: function(data, textStatus, XMLHttpRequest){ alert("Data ...

"Creating a Miniview Panel on a Fabric Canvas: A Step-by-Step Guide

Is there a way to add a mini view panel to my Fabric Canvas like shown in this image MiniView Panel? I want a panel in the corner of my canvas that displays the entire layout. Similar to the panel on this website . ...

After logging in, I am unable to redirect to another PHP page as the login form simply reloads on the same page

Lately, I've encountered an issue that has persisted for a few days. The login validation is functioning flawlessly. However, the problem arises when attempting to redirect to another page, specifically 'index.php', after logging in. Instead ...

Creating a layered effect by overlaying one image on top of another in an HTML5

Currently, I am facing an issue with drawing a level field inside my canvas. The images of the tank and enemies are being drawn underneath the field image, which is causing some problems as they should actually be moving above the field. Here is a link t ...

Securely encoding information with PHP and decrypting it using JavaScript

I'm currently working with 2 servers. My goal is to generate a pair of keys, store the private key in local storage, and send the public key to my PHP server. The main objective is to encrypt data using the public key in PHP and decrypt it using Jav ...

An issue arising with the TypeScript antlr4ts listener type

I am currently attempting to incorporate the antlr4 parser into an angular project. Within a dataservice class, there is a function being called that appears as follows: parseRule() { const ruleString = ' STRING TO PARSE'; const inputS ...

Importing an external JSON file into a ChartJs chart

As a newcomer to using libraries for drawing charts in JavaScript, I recently started playing around with Chartjs. However, I'm having trouble figuring out how to use getJson or any other method to load my json object and update the labels and data. I ...

Creating HTML input elements dynamically using Javascript

<body> <form action="insertquestion.php" method="POST"> <script> function generateInputs(){ var prefix = "answer"; var number = 1; for(var i = 0; i < 5; i++){ ...

Setting up a straightforward static server using node.js

var express = require('express'); var app = express(); app.use('/', express.static('./')); app.listen(80); Error message encountered when running "node server.js" in the CLI: events.js:160 throw er; // Unhandled ...

Sophisticated web applications with Ajax functionalities and intricate layouts powered by MVC frameworks

I am looking to integrate an ajax-driven RIA frontend, utilizing JQuery layout plugin (http://layout.jquery-dev.net/demos/complex.html) or ExtJs (http://www.extjs.com/deploy/dev/examples/layout/complex.html), with... a PHP MVC backend, potentially using ...

Is there a way for me to showcase the latitude and longitude retrieved from JSON data on a Google Map using modals for each search result in Vue.js?

After receiving JSON data with search results, each containing latitude and longitude coordinates, I am attempting to display markers on a Google map modal when clicking "View Map". However, the code I'm using is not producing the desired outcome. Th ...

Randomize the array of images in Nuxt every time the page is reloaded to display a variety of logos in the carousel

I've set up a carousel of logos, with the intention to randomize their order every time the page reloads. The challenge is that my layout only allows for 10 images to be displayed at once. While it seems like everything is functioning correctly, I&ap ...

Guide on validating a dropdown using template-driven forms in Angular 7

Having trouble validating a dropdown select box, possibly due to a CSS issue. Any suggestions on how to fix this validation problem? Check out the demo here: https://stackblitz.com/edit/angular-7-template-driven-form-validation-qxecdm?file=app%2Fapp.compo ...