Trouble Loading TypeScript Class in Cast Situation

I've encountered an issue with my TypeScript model while using it in a cast. The model does not load properly when the application is running, preventing me from accessing any functions within it.

Model

export class DataIDElement extends HTMLElement {
    get dataID(): number {
        var attributes: NamedNodeMap = this.attributes;
        var dataIDAttribute: Attr = attributes.getNamedItem("data-id");

        if (!dataIDAttribute) { 
            //throw error
        }

        var value: number = Number(dataIDAttribute.value);
        return value;
    }
}

Angular Component (Where model is being imported)

import { DataIDElement } from '../../models/dataIdElement';

export class PersonComponent
{
    personClicked(event: KeyboardEvent): void {
        var element: DataIDElement = <DataIDElement>event.target;

        // This code always returns undefined (model isn't loaded)
        var personID: number = element.dataID;
    }
}

Answer №1

When you use a type assertion in TypeScript, you are essentially informing the compiler about the type of a variable. In the case mentioned, event.target is being asserted as type DataIDElement, but it doesn't create a new instance of DataIDElement.

To actually instantiate a new object of type DataIDElement, you would need to use the new keyword.

An example implementation of DataIDElement could be:

export class DataIDElement extends HTMLElement {
    constructor(private target: HTMLElement) {}
    get dataID(): number {
        var attributes: NamedNodeMap = this.target.attributes;
        var dataIDAttribute: Attr = attributes.getNamedItem("data-id");

        if (!dataIDAttribute) { 
            //throw error
        }

        var value: number = Number(dataIDAttribute.value);
        return value;
    }
}

This is how you could use DataIDElement:

import { DataIDElement } from '../../models/dataIdElement';

export class PersonComponent
{
    personClicked(event: KeyboardEvent): void {
        var element: DataIDElement = new DataIDElement(event.target);

        // This code always returns undefined (model isn't loaded)
        var personID: number = element.dataID;
    }
}

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

Executing Java Script on several identical elements

Currently, I am facing an issue with my JavaScript function that is supposed to toggle the display of titles within elements. The function works perfectly fine on the first element, but it does not work on the other elements. Here is the code snippet: ...

Guidelines for implementing more rigorous type checks in TypeScript:

I am looking to enhance the code validation process and eliminate any implicit 'any' types. To achieve this, I have set "strict": true in my tsconfig.json. { "compilerOptions": { "target": "ES5", ...

How to Ensure Screen Opens in Landscape Mode with Phaser3

https://i.stack.imgur.com/keCil.pngIn my Phaser3 game, I am trying to achieve the functionality where the game opens horizontally in a webview without requiring the user to rotate their phone. The vertical photo below shows the game in its current state. W ...

I am looking to generate an array with key-value pairs from an object that will be seen in the examination

I have a task that involves configuring a table and creating objects with key-value pairs for each key. type KeyValuePair<T> = {/** ... */}; let userKeyValuePair :KeyValuePair<{id:number,userName:string}>; // => {key:'id',value: ...

Display options through numerical selection

I have been attempting to construct something, but I'm encountering difficulties. My goal is to create a functionality where entering a number in an input field will generate that many additional input fields. I've attempted to implement this us ...

Align the body of the table with the header after populating the table with values

Issue : The data in the table body is misaligned with the headers of each column. Solution : var test_insert1 = '<tr>' + '<td class="td-trad-9">762261</td>' + '<td class="td-trad-7">1.16176&l ...

Implementing real-time time updates using php ajax technology

It's fascinating how websites can update the time dynamically without using ajax requests. I currently have a comment system in place. $('#comment').click(function(){ $.post(url,{ comment : $(this).siblings('textarea.#commen ...

Store the content of an HTML div using HTML5 Drag and Drop functionality in a MYSQL database

Here's a simple scenario: I have 3 small divs (1, 2, 3) and I want to place them inside 3 other divs (4, 5, 6). That's no issue, but then I need to store the data in MySQL, such as 4-1, 5-2, 6-3 for instance. I can use JavaScript to display the n ...

UI-Router: What is the best way to access a page within my project without adding it as a State?

Currently in the process of learning Angular and UI-Router. Initially, I followed the advice of many and chose to utilize UI-Router. In my original setup, the login page was included in all States. However, I decided it would be best to keep it as a separ ...

Issue with dynamically filling a form field using ValidityState

I have been utilizing the ValidityState interface for client-side form validation, but I've encountered an issue. Whenever my form is populated programmatically, such as after making a call to a third-party API, the tooLong state always returns false, ...

The Clerk authMiddleware() function has been defined in the middleware.ts file located at the root of the application, but it is not being utilized

import { authMiddleware } from "@clerk/nextjs"; export default authMiddleware({}); export const config = { matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)&apos ...

Element eradicated by mysterious force - what is the reason behind this destruction?

I encountered a peculiar issue while working on a JS game demo. For some reason, one of the functions is unexpectedly deleting the container element (even though I didn't intend for it to do so). This function usually creates another element inside th ...

Why bother re-rendering components in React that haven't had any changes in their state?

Within my main component, I have both a state and a static component nested inside. An issue arises when the state changes and triggers a re-render of the main component, causing the static component to also re-render unnecessarily. import { useState } fro ...

Having trouble with integrating Firebase and Vue database

While attempting to integrate Firebase with my Vue 4 application, I encountered the following error: Uncaught TypeError: db__WEBPACK_IMPORTED_MODULE_1_.default.database is not a function The versions I am using are: "firebase": "^9.0.0&qu ...

The functionality of Material UI tooltip is not functioning properly when accessed on mobile devices

Attempting to transform Tooltip into a controlled component that relies on the onClick event. While this setup works well on mobile and web, it loses its original functionality of showing the Tooltip on hover. Is there a way to make the Tooltip function ...

Prevent clicks from passing through the transparent header-div onto bootstrap buttons

I have a webpage built with AngularJS and Bootstrap. It's currently in beta and available online in (German and): teacher.scool.cool simply click on "test anmelden" navigate to the next page using the menu This webpage features a fixed transparent ...

Why am I getting the "Cannot locate control by name" error in my Angular 9 application?

Currently, I am developing a "Tasks" application using Angular 9 and PHP. I encountered a Error: Cannot find control with name: <control name> issue while attempting to pre-fill the update form with existing data. Here is how the form is structured: ...

`Optimizing Django by using multiple room relationships to save formset related models`

I need help with saving a formset that involves two models in a many-to-many relationship. When I open the page, two forms are displayed but after filling them out and clicking "Add", the fields for "phone" and "client_name" get cleared and the form is not ...

Setting up JavaScript imports in Next.js may seem tricky at first, but with

Whenever I run the command npx create-next-app, a prompt appears asking me to specify an import alias. This question includes options such as ( * / ** ) that I find confusing. My preference is to use standard ES6 import statements, like this: import Nav f ...

Ways to simulate file operations in sinon?

I have a function that unzips a file from the directory, and it is working perfectly fine. index.js const unZip = async (zipFilePath, destDir) => { await util.promisify(fs.mkdir)(destDir); return new Promise((resolve, reject) => { fs.create ...