Files
renovate/tools/lint/rules/prefer-coerce-object.ts
Sebastian Poxhofer c32e2391a0 refactor(linters): add prefer-coerce-object rule (#45493)
Refs #45216

The object counterpart to `prefer-coerce-array`: `x ?? {}` becomes
`coerceObject(x)`. The rule flags a `??` whose default is a bare `{}`
literal, so a populated default or an asserted `({} as Foo)` still
passes; a `x ?? y ?? {}` chain maps onto `coerceObject(x, y)`.

Every hit across `lib/` converted cleanly, so no disable comments were
needed.
2026-08-28 09:27:59 +00:00

34 lines
924 B
TypeScript

import { defineRule } from '@oxlint/plugins';
/**
* Flags `x ?? {}` in favour of `coerceObject(x)` from `lib/util/object.ts`.
* A chain like `x ?? y ?? {}` maps onto the two-argument `coerceObject(x, y)`.
*
* Only a bare `{}` literal counts: `x ?? { a: 1 }` keeps a meaningful default,
* and `x ?? ({} as Foo)` carries an assertion the helper cannot express.
*/
export default defineRule({
meta: {
type: 'suggestion',
messages: {
preferCoerceObject:
'Use `coerceObject()` from `lib/util/object.ts` instead of `?? {}`.',
},
},
createOnce(context) {
return {
LogicalExpression(node) {
if (node.operator !== '??') {
return;
}
if (
node.right.type === 'ObjectExpression' &&
node.right.properties.length === 0
) {
context.report({ node, messageId: 'preferCoerceObject' });
}
},
};
},
});