amilajack / amilajack/eslint-plugin-compat
Consider `typeof` in feature detection
- Ngôn ngữ chính
- TypeScript
- Star
- 3.2k
- Fork
- 115
- Chỉ số merge pull request
- Không có pull request nào được merge trong 30 ngày
Mô tả
The addition of feature detection in https://github.com/amilajack/eslint-plugin-compat/pull/327 is great. I think it would make a great addition to check for `typeof`.
```js
if (fetch) {
fetch()
}
if (localStorage); // ReferenceError
if (window.localStorage); // DOMException: Storage not allowed
```
This is generally unsafe as this would cause a ReferenceError if `fetch` did not exist. Instead, the safe and environment-agnostic way to check support for a built-in API is through `typeof`:
```js
if (typeof fetch !== 'undefined') {
fetch();
}
if (typeof fetch === 'function') {
fetch();
}
if (typeof document !== 'undefined' && document.getElementById('qunit')) {
init(document.getElementById('qunit-header'));
}
```
There is support for a different safe-ish mechanism already, namely `window.fetch` however I generally avoid this because 1) This can cause an exception if the property has a getter that denies access such as `window.localStorage` in some browser's private mode, and 2) is slightly slower, and 3) relies on there being a `window` global which doesn't work for isomorphic code that is agnostic of browser version and JS engine (e.g. also in Node.js, SpiderMonkey, especially versions prior to `globalThis`).
The `typeof` approach always works and seems to be common for this purpose.
I would recommend checking for either `!== 'undefined'` or `===` with anything other than `'undefined'` (e.g. "object", "number", someVariable). I've not worked much with ESTree before, but I'd like to learn and would be interested in contributing a patch.
Hướng dẫn đóng góp
Đánh giá
Issue này chưa được đánh giá.