0

jQuery.type() is deprecated in jQuery 3.3 and above. When refactoring older code that uses this API, what should I use instead of jQuery.type()?

For example, one of the plugins my page relies on uses the $.type() API as illustrated below.

if ($.type(button) !== 'object') {
     throw new Error('button with key "' + key + '" must be an object');
}

I'd like to replace it with something that isn't deprecated.

Ectropy
  • 1,533
  • 4
  • 20
  • 37
  • Well, just going off of the variable name, potentially `!button || !button.tagName || button.tagName !== 'BUTTON'` – Taplar Jun 08 '20 at 21:30
  • 1
    https://j11y.io/jquery/#v=1.11.2&fn=jQuery.type You could also look at the source code and see what they were doing – Taplar Jun 08 '20 at 21:32

2 Answers2

1

From your link I clicked on the depreciated version and got here: https://api.jquery.com/category/version/3.3/

That let me click the release notes link: https://blog.jquery.com/2018/01/19/jquery-3-3-0-a-fragrant-bouquet-of-deprecations-and-is-that-a-new-feature/

Where I found the github commits for the change: https://github.com/jquery/jquery/issues/3605 https://github.com/jquery/jquery/commit/1ea092a54b00aa4d902f4e22ada3854d195d4a18

They depreciated this because the 'class2type' table didn't handle new data types to the point of being useless. They revert their own internal code to use vanilla js typeof - I assume that's the expected change for your code base.

Also, see here: Difference between JQuery.type and typeof, which is faster Namely the second answer for the loss of detail in reading certain types. If that's problematic for you, I guess it's just workarounds like the kind @Taplar suggested / your answer to this question(Edit/Update).

TCooper
  • 1,545
  • 1
  • 11
  • 19
0

It appears that based on this response, you can use typeof yourVariable === 'object' && yourVariable !== null to determine if a variable is an object (note that you must also check that it is not a null since JS considers nulls to be objects.)

Since we need to throw an error if the button variable is NOT an object, we should be able to change the code to use typeof like so:

if (typeof button !== 'object' || typeof button === null) {
     throw new Error('button with key "' + key + '" must be an object');
}

(Note that we have to throw an error if the button var is null, because while JavaScript typeof considers nulls to be objects, it's not the type of object we're looking for.)

In short, you'll want to replace jQuery.type() with a typeof comparison.

Ectropy
  • 1,533
  • 4
  • 20
  • 37