sindresorhus/eslint-plugin-unicorn

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

Closed

#2,178 opened on Jul 19, 2023

 (2 comments) (2 reactions) (0 assignees)JavaScript (468 forks)user submission
help wantednew rule

Repository metrics

Stars
 (5,022 stars)
PR merge metrics
 (Avg merge 1d 16h) (399 merged PRs in 30d)

Description

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

Contributor guide