Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/conditional-object-spreads.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@frontify/eslint-config-basic': minor
'@frontify/eslint-config-react': minor
'@frontify/eslint-plugin': patch
'@frontify/oxlint-config-basic': minor
'@frontify/oxlint-config-react': minor
---

ESLint and Oxlint now report conditional and logical spreads in object literals and JSX props as errors. Build a named object and use an `if` statement to assign its optional fields before spreading it.
4 changes: 3 additions & 1 deletion packages/eslint-config-basic/eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ export default defineConfig(
},
extends: [eslintPluginImportX.flatConfigs.typescript],
plugins: {
'@frontify': frontifyPlugin,
// Where we want to customize few part and not use recommended
unicorn: eslintPluginUnicorn,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
Expand All @@ -170,6 +171,8 @@ export default defineConfig(
'import-x/resolver-next': [createTypeScriptImportResolver(), createNodeResolver()],
},
rules: {
'@frontify/no-conditional-object-spread': 'error',

// Eslint (base)
'@stylistic/linebreak-style': ['error', 'unix'],
'@stylistic/eol-last': ['error', 'always'],
Expand Down Expand Up @@ -340,7 +343,6 @@ export default defineConfig(
{
// TypeScript files
files: ['**/*.ts', '**/*.tsx', '**/*.mts', '**/*.cts'],
plugins: { '@frontify': frontifyPlugin },
rules: {
'@frontify/no-inline-param-type': 'error',

Expand Down
2 changes: 2 additions & 0 deletions packages/eslint-plugin/index.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* (c) Copyright Frontify Ltd., all rights reserved. */

import jsxShorthandBoolean from './rules/jsx-shorthand-boolean.mjs';
import noConditionalObjectSpread from './rules/no-conditional-object-spread.mjs';
import noInlineParamType from './rules/no-inline-param-type.mjs';

export default {
Expand All @@ -9,6 +10,7 @@ export default {
},
rules: {
'jsx-shorthand-boolean': jsxShorthandBoolean,
'no-conditional-object-spread': noConditionalObjectSpread,
'no-inline-param-type': noInlineParamType,
},
};
2 changes: 2 additions & 0 deletions packages/eslint-plugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@
"files": [
"index.mjs",
"rules/jsx-shorthand-boolean.mjs",
"rules/no-conditional-object-spread.mjs",
"rules/no-inline-param-type.mjs"
],
"scripts": {
"test": "node --test 'rules/**/*.test.mjs'"
},
"devDependencies": {
"@typescript-eslint/parser": "^8.60.0",
"@typescript-eslint/types": "8.60.0",
"eslint": "^10.4.1"
},
"publishConfig": {
Expand Down
55 changes: 55 additions & 0 deletions packages/eslint-plugin/rules/no-conditional-object-spread.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/* (c) Copyright Frontify Ltd., all rights reserved. */

// @ts-check

/** @typedef {import('@typescript-eslint/types').TSESTree.SpreadElement | import('@typescript-eslint/types').TSESTree.JSXSpreadAttribute} ObjectOrPropSpread */

const OBJECT_OR_PROP_SPREAD = 'ObjectExpression > SpreadElement, JSXSpreadAttribute';
const CONDITIONAL_EXPRESSIONS = new Set(['ConditionalExpression', 'LogicalExpression']);
const EXPRESSION_WRAPPERS = new Set([
'ParenthesizedExpression',
'TSAsExpression',
'TSTypeAssertion',
'TSSatisfiesExpression',
'TSNonNullExpression',
'ChainExpression',
]);
const ASSIGN_FIELDS_MESSAGE_ID = 'assignFields';

/** @satisfies {import('eslint').Rule.RuleModule} */
const noConditionalObjectSpread = {
meta: {
type: 'problem',
schema: [],
messages: {
[ASSIGN_FIELDS_MESSAGE_ID]: 'Assign conditional fields with an if statement before spreading the object.',
},
},
create(context) {
return {
/**
* Reports conditions that supply fields to an object.
* @param {import('eslint').JSSyntaxElement} node - The spread in an object literal or JSX props.
*/
[OBJECT_OR_PROP_SPREAD](node) {
// The selector limits the listener to the two nodes with a spread argument.
const spread = /** @type {ObjectOrPropSpread} */ (node);
let value = spread.argument;

while (
EXPRESSION_WRAPPERS.has(value.type) &&
'expression' in value &&
typeof value.expression === 'object'
) {
value = value.expression;
}

if (CONDITIONAL_EXPRESSIONS.has(value.type)) {
context.report({ node, messageId: ASSIGN_FIELDS_MESSAGE_ID });
}
},
};
},
};

export default noConditionalObjectSpread;
86 changes: 86 additions & 0 deletions packages/eslint-plugin/rules/no-conditional-object-spread.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/* (c) Copyright Frontify Ltd., all rights reserved. */

import * as parser from '@typescript-eslint/parser';
import { RuleTester } from 'eslint';

import plugin from '../index.mjs';

const rule = plugin.rules['no-conditional-object-spread'];
const ruleTester = new RuleTester({ languageOptions: { parser } });
const assignFieldsError = { messageId: 'assignFields' };

const conditionalObjectSpreads = [
{
name: 'reports a conditional spread in an object literal',
code: 'const props = { ...base, ...(ready ? additional : {}) };',
},
{
name: 'reports a logical AND spread in an object literal',
code: 'const props = { ...(ready && additional) };',
},
{
name: 'reports a logical OR spread in an object literal',
code: 'const props = { ...(additional || defaults) };',
},
{
name: 'reports a nullish coalescing spread in an object literal',
code: 'const props = { ...(additional ?? defaults) };',
},
{
name: 'reports a conditional JSX prop spread',
filename: 'example.jsx',
code: 'const view = <Panel {...(ready ? additional : defaults)} />;',
},
{
name: 'reports a logical JSX prop spread',
filename: 'example.tsx',
code: 'const view = <Panel {...(ready && additional)} />;',
},
{
name: 'reports a conditional JSX prop spread inside TypeScript wrappers',
filename: 'example.tsx',
code: 'const view = <Panel {...((ready ? additional : defaults) as Props satisfies Props)} />;',
},
{
name: 'reports a conditional spread through an angle-bracket type assertion',
filename: 'example.ts',
code: 'const props = { ...(<Props>(additional ?? defaults)) };',
},
{
name: 'reports a conditional spread through a non-null assertion',
filename: 'example.ts',
code: 'const props = { ...(ready ? additional : defaults)! };',
},
];

ruleTester.run('no-conditional-object-spread', rule, {
valid: [
{ name: 'accepts an object merge', code: 'const props = { ...base, ...additional };' },
{ name: 'accepts a JSX prop spread', filename: 'example.jsx', code: 'const view = <Panel {...props} />;' },
{
name: 'accepts a ternary inside a call that supplies the spread value',
code: 'const props = { ...getProps(ready ? additional : defaults) };',
},
{
name: 'accepts a conditional array spread',
code: 'const items = [...base, ...(ready ? additional : [])];',
},
{
name: 'accepts a logical array spread',
code: 'const items = [...(additional ?? defaults)];',
},
{
name: 'accepts a conditional argument spread',
code: 'invoke(...(ready ? additional : []));',
},
{
name: 'accepts a logical argument spread',
code: 'invoke(...(additional || defaults));',
},
{
name: 'accepts a conditional constructor argument spread',
code: 'const item = new Item(...(ready ? additional : []));',
},
],
invalid: conditionalObjectSpreads.map((testCase) => ({ ...testCase, errors: [assignFieldsError] })),
});
1 change: 1 addition & 0 deletions packages/oxlint-config-basic/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,7 @@ export default defineConfig({
node: true,
},
rules: {
'@frontify/no-conditional-object-spread': 'error',
'no-empty': 'error',
'no-useless-catch': 'error',
'prefer-template': 'error',
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.