Convert jQuery to Typescript

0

I'm having several problems converting this snippet of code with jQuery using only Typescript.

 function addTourOverlay() {
        if ($('#tour-overlay').length === 0) {
          $('body').prepend('<div id="tour-overlay"></div>');
        }
    resizeOverlay();
  }

  function resizeOverlay() {
    var window_height = $(window).height;
    var window_width = $(window).width;
    $('#tour-overlay').height(window_height).width(window_width);
  }

Currently the conversion looks like this:

addTourOverlay2() {
    if (document.querySelectorAll('#tour-overlay').length === 0) {
        let newDiv = document.createElement('div'); 
        newDiv.id = 'tour-overlay';
        let body = document.getElementsByTagName('body');
        newDiv.appendChild(body);
      }
    this.resizeOverlay();
  }

  resizeOverlay() {
    let window_height = screen.height;
    let window_width = screen.width;
    document.getElementById('#tour-overlay').style.height = window_height; 
    document.getElementById('#tour-overlay').style.width = window_width;
  }

I'm getting the following errors: Type 'number' can not be assigned to type 'string'. (lines 36 and 37)

The argument of type 'NodeListOf' is not attributable to the parameter of type 'Node'.   The 'baseURI' property is missing in type 'NodeListOf'. (Line 28)

    
asked by anonymous 18.09.2018 / 16:22

1 answer

1
addTourOverlay2() {

  // (1) 
  if (document.querySelectorAll('#tour-overlay').length === 0) {

    let newDiv = document.createElement('div');
    newDiv.id = 'tour-overlay';
    let body = document.getElementsByTagName('body');

    // (2)
    newDiv.appendChild(body);

  }
  this.resizeOverlay();
}

resizeOverlay() {
  let window_height = screen.height;
  let window_width = screen.width;

  // (3 e 4)
  document.getElementById('#tour-overlay').style.height = window_height;
  document.getElementById('#tour-overlay').style.width = window_width;

}

Starting with some trivial failures:

  • If you search for the id you are expected to return only one element, not several ; so instead of querySelecorAll , you can use querySelector only (or getElementById );

  • You added body to newDiv ; I believe the correct one would be newDiv in body ;

  • When using getElementById you do not need to enter the # character, only the value of the attribute;

  • See 3;

  • About the error

      

    Type 'number' can not be assigned to type 'string'. (lines 36 and 37)

    This comes from Typescript, which takes into account the data types. In this case, screen.height is a numeric value, but element.style.height is a string . What you need to do is declare cast between types:

    document.getElementById('#tour-overlay').style.height = <string> window_height; 
    document.getElementById('#tour-overlay').style.width = <string> window_width;
    // Aqui você informa o cast da variável ----------------^
    
        
    18.09.2018 / 17:00