Home > Mobile >  Convert jQuery ready function to TypeScript
Convert jQuery ready function to TypeScript

Time:05-19

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":

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?

CodePudding user response:

function myFunc() { }

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

You can type it like this.

  • Related