Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert jQuery ready function to TypeScript

I’m trying to replace some old code that uses jQuery, to the new way without it.

The old code, using the ready function:

function myFunc() { }

$(function() {
  myFunc();
});

I found this equivalent at "You Might Not Need jQuery":

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function myFunc() { }

function ready(fn) {
  if (document.readyState != 'loading')
    fn();
  else
    document.addEventListener('DOMContentLoaded', fn);
}
ready(myFunc);

I’m using TypeScript, so it complains about fn being implicit any. I’d like to avoid that.

I tried: fn: Function, but the compiler complains about the overloads to addEventListener, and I’m unsure how to handle it.

How do I avoid any?

>Solution :

function myFunc() { }

function ready(fn:() => void) {
  if (document.readyState != 'loading')
    fn();
  else
    document.addEventListener('DOMContentLoaded', fn);
}
ready(myFunc);

You can type it like this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading