sindresorhus/eslint-plugin-unicorn

Rule proposal: `require-proxy-set-returns-true`

Chiusa

#2178 aperta il 19 lug 2023

 (2 commenti) (2 reazioni) (0 assegnatari)JavaScript (468 fork)user submission
help wantednew rule

Metriche repository

Star
 (5022 stelle)
Metriche merge PR
 (Merge medio 1g 16h) (399 PR mergiate in 30 g)

Descrizione

Description

According to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/set#return_value

If the set() method returns false, and the assignment happened in strict-mode code, a TypeError will be thrown.

The following code throws.

(function () {
    "use strict";
    const proxy = new Proxy({}, {
        set(target, property, value) {
        }
    });
    proxy.foo = 'bar'
})()

// Uncaught TypeError: 'set' on proxy: trap returned falsish for property 'foo'

This rule enforce the set to explicitly return true. This rule also allow return Reflect.set() call.

Fail

const proxy = new Proxy({}, {
    set(target, property, value) {
        target[property] = value;
    }
});
const proxy = new Proxy({}, {
    set(target, property, value) {
        target[property] = value;
        return 1; // Will work, but should be `true` to be clear.
    }
});

Pass

const proxy = new Proxy({}, {
    set(target, property, value) {
        target[property] = value;
        return true;
    }
});
const proxy = new Proxy({}, {
    set(target, property, value) {
        return Reflect.set(...arguments);
    }
});

Additional Info

No response

Guida contributor