TS2339 error: Transitioning from JavaScript to TypeScript bug


Struggling with errors in the TypeScript implementation, specifically:

  • Error TS2339: Property 'style' does not exist on type 'Element'. (dashboard.component.ts line 49)
  • Error TS2339: Property 'textContent' does not exist on type 'EventTarget'. (dashboard.component.ts line 50)

Although this code works seamlessly as a JavaScript function, it encounters the mentioned errors when adapted for TypeScript. I have attempted changing 'var' to 'let' and adding '.', but no luck so far. Any other suggestions or solutions would be greatly appreciated. Thank you.

dashboard.ts

var w = document.getElementById('wrapper');
var button = document.getElementById('randomize');
var image = w.children; // inner elements, your quotes divs

// a function to hide all divs
var hideDivs = function(divs) {
  for (var div of divs) {
    div.style.display = 'none';
  }
}

hideDivs(image); // hide all initially

// on click
button.addEventListener('click', function(event) {
  var rnd = Math.floor(Math.random() * image.length); // get random index
  hideDivs(image); // hide all quotes
  image[rnd].style.display = 'block'; // show random quote
  event.target.textContent = 'Click one more time!'; // set button text. event.target is the button you've clicked
})

dashboard.html

  <div id="wrapper">
  <div class="image" img scr='../../assets/mood.jpg'></div>
  <div class="image" img scr='../../assets/mood.jpg'></div>
  <div class="image" img scr='../../assets/mood.jpg'></div>
  <div class="image" img scr='../../assets/mood.jpg'></div>
  <div class="image" img scr='../../assets/mood.jpg'></div>
</div>
<button id='randomize'>Next</button>

Answer №1

The issue lies in the fact that the variable target is defined as type EventTarget, while an element of image, which is a HTMLCollection, is defined as type Element. Both properties you intend to access are actually defined on HTMLElement. To resolve this, you can use a type assertion to inform the compiler that in your scenario, both of these should be considered as HTMLElement.

// when clicked
button.addEventListener('click', function (event) {
    var rnd = Math.floor(Math.random() * image.length); // obtain random index
    hideDivs(image); // conceal all quotes

    (image[rnd] as HTMLElement).style.display = 'block'; // display random quote
    (event.target as HTMLElement).textContent = 'Click one more time!'; // set button text. event.target refers to the button that was clicked
})

You may also want to ensure that hideDivs is correctly typed as follows:

// method to hide all div elements
const hideDivs = function (divs: HTMLCollection) {
    for (var div of divs) {
        (div as HTMLElement).style.display = 'none';
    }
}

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

Unable to fetch source for HTML img tag

I am struggling with using jQuery to retrieve the src attribute of an image when it is clicked. Unfortunately, my current code does not output anything to the console and returns undefined when I try to manipulate it in the browser console. I do not have m ...

Creating aesthetically pleasing URLs from data: A simple guide

Can someone help me transform this data into a pretty URL? I am looking for something similar to Appreciate the assistance! :) var x = {data1, data2, data3}; $.ajax({ url: 'https://mywebsite.com/admin/leads/count/', data: x, type: &a ...

How to prevent uncaught errors when checking for undefined in if statements and dealing with undefined items

It appears that there are not many oboe tags being used on SO, but any assistance with this general JavaScript question regarding handling uncaught errors for undefined would be greatly appreciated!~ I am currently utilizing Oboe.js to stream data to a we ...

MongoJS Node findOne query inaccurately returns empty result set

Utilizing MongoJS: https://github.com/mafintosh/mongojs Retrieves all data Returns an empty array</p> The database contains the data I am looking for. I've also tried searching using a different key (such as name). Why is it unable to locate ...

Discover the power of pdf.js for effective online browsing!

Currently, I am using pdf.js to display a PDF file in my Ionic App. Instead of utilizing viewer.js and viewer.html, I have created a custom layout with a unique search bar. One feature I am looking to implement is the ability to highlight terms within the ...

Using Regular Expressions in Express routing

Does anyone have experience serving a file with a dynamic hash in its name on a specific route? The file is named like workbox-someHash.js and the hash changes every time the app is deployed. I attempted to serve it using the following code snippets: &qu ...

When the textbox fails validation, it should display an error message within the same textbox and prevent the user from proceeding to another textbox

Here is a JavaScript function and a textbox in the code snippet below. The validations work perfectly. The goal is to clear the textbox value and keep the cursor in the same textbox if the validation fails, without moving to other controls. JS: function ...

Issue with ng2-charts not rendering properly on the client side when utilized in Angular version 2.0.0-beta-17

Struggling with using ng2-charts in my Angular 2 app and encountering some challenges. app.ts import {Component} from 'angular2/core'; import {CHART_DIRECTIVES} from 'ng2-charts/ng2-charts'; @Component({ selector: & ...

Just starting out with Angular - facing issues with setting up in eclipse

I'm attempting to create a test Angular project in Eclipse by copying the three files from the Angular website https://docs.angularjs.org/api/ng/directive/ngController into my Eclipse project. I initially created it as a static web project and then co ...

I'm curious to understand the inner workings of how chained functions operate in JavaScript when there is a prototype function included in the chain

Looking to separate the chained calls, starting from: request .post('/upload') .attach('image1', 'path/to/felix.jpeg') .attach('image2', imageBuffer, 'luna.jpeg') .field('caption', 'M ...

SyntaxError in ExpressJS: Encountered an unexpected token "C"

I'm having trouble saving my string to a comma-separated array. When I attempt to use the JSON.parse method, I encounter an error while sending a post request and trying to save a record: SyntaxError: Unexpected token c at Object.parse (native) ...

Issue with uploading files in headless mode using Webdriverio V9

After upgrading from v8 to v9, I encountered an issue with file uploads in headless mode. The code worked fine in non-headless mode, but failed in headless mode. I would appreciate any assistance with this. capabilities: [ { maxInst ...

Implement a sliding effect for the navigation menu

I'm trying to figure out how to make this menu slide in when the hamburger menu is clicked. The background of the menu is an SVG, not just a shape. Does anyone have any suggestions or ideas on how I can achieve this effect? For reference, here is the ...

No action is triggered after submitting AJAX data in a WordPress environment

I'm currently working on developing a WordPress plugin that requires querying the database. However, I am facing challenges in getting it to function properly. Here is the code snippet that I have attempted: jQuery('#demo_ajax').submit(func ...

How to send information from parent component to child in Angular 15

Currently, I am in the process of learning Angular, so please bear with me if my terminology is not entirely accurate. Below, you will find a complete output at the end of this post. At present, I have code that successfully triggers a hard-coded modal. H ...

How to navigate through list items in React without triggering a re-render

Currently, I am in the process of learning React. Let's consider a scenario where I have a component called ListContainer that renders multiple ListItems. My goal is to keep track of which ListItem is currently selected, display it in a different colo ...

During model update, AngularJS experienced a loss of CSS class in DOM re-rendering

My challenge involves managing a table that dynamically updates via WebSocket messages, causing the selection state to be lost. The rows in this table loop through model data, and upon clicking a cell, all cells in the same row toggle to have an .active cl ...

Enhancing event listener using AngularJS and Jasmine: spying on callback functions

Can someone assist me with spyOnning a method connected to an event using scope.$on in a factory service, using Jasmine? The actual method is being called instead of the spy. Here is a plinkr I created showcasing the issue: http://plnkr.co/edit/2RPwrw?p=pr ...

JavaScript setInterval causing exception due to syntax error

I am trying to play an audio file every second using the code below. The audio file is one second long and consists of a ticking sound. However, when I run the code, it only plays once before throwing an error in the console. My goal is to have the audio p ...

Is it necessary for an embedded YouTube video to automatically play with sound?

My current project involves developing a Web Application where the client has specified that videos must autoplay with sound when a user visits it. Here is a snippet of what I have implemented: HTML: <embed id="video1" src="" wmode="transparent" type= ...