Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
a97e52e
feat(eslint-plugin): [no-useless-default-assignment] add rule
ulrichstark Oct 25, 2025
4a8ef6b
support function parameters without type annotation
ulrichstark Oct 25, 2025
7637497
fix false positives
ulrichstark Oct 25, 2025
7a7b334
fixing more false positives
ulrichstark Oct 25, 2025
527b367
enable rule in repo to dogfood
ulrichstark Oct 25, 2025
010c166
cleanup code and increase code coverage
ulrichstark Oct 25, 2025
ff7bd0b
cleanup code and add column numbers to tests
ulrichstark Oct 25, 2025
8d29d31
add tests to increase test coverage
ulrichstark Oct 25, 2025
df51d1c
remove option allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing
ulrichstark Nov 4, 2025
0526062
remove comments at each test case
ulrichstark Nov 4, 2025
90d121a
remove rule from rulesWithComplexOptionHeadings
ulrichstark Nov 4, 2025
9b55fb2
update snapshot
ulrichstark Nov 4, 2025
422a704
Update packages/eslint-plugin/docs/rules/no-useless-default-assignmen…
ulrichstark Nov 4, 2025
16ff0d6
Update packages/eslint-plugin/docs/rules/no-useless-default-assignmen…
ulrichstark Nov 4, 2025
4c40bfb
add rule to strict config
ulrichstark Nov 4, 2025
def0e8a
Merge branch 'main' into feat(eslint-plugin)---no-useless-default-ass…
ulrichstark Nov 4, 2025
6bef7fa
turn suggestion into fix
ulrichstark Nov 5, 2025
299249e
add more test cases and make them pass
ulrichstark Nov 5, 2025
242883a
make example code easier to understand and add tuple example
ulrichstark Nov 5, 2025
7d7a636
increase test coverage
ulrichstark Nov 5, 2025
6d7f339
Merge branch 'main' into feat(eslint-plugin)---no-useless-default-ass…
ulrichstark Nov 19, 2025
f5fb05c
remove self-apparent comments
ulrichstark Nov 19, 2025
ba7e074
use createRuleTesterWithTypes
ulrichstark Nov 19, 2025
f64f7d7
use isFunction
ulrichstark Nov 19, 2025
03c49ff
remove unnecessary schema item
ulrichstark Nov 19, 2025
746f9f7
update snapshot
ulrichstark Nov 19, 2025
a4d42f2
support nested destructuring
ulrichstark Nov 22, 2025
79b3f39
add valid test case
ulrichstark Nov 22, 2025
89c230f
report contextual assignments and more test cases
ulrichstark Nov 22, 2025
cf4d876
Merge branch 'main' into feat(eslint-plugin)---no-useless-default-ass…
ulrichstark Nov 22, 2025
72cae2d
report undefined as useless default assignment
ulrichstark Nov 23, 2025
39802f6
add test cases, refactor and use nullThrows to increase test coverage
ulrichstark Nov 24, 2025
37ce842
remove from eslint.config.mjs
ulrichstark Nov 26, 2025
33c859e
make "when not to use it" more relevant to this rule
ulrichstark Nov 26, 2025
052981c
Merge branch 'main' into feat(eslint-plugin)---no-useless-default-ass…
ulrichstark Nov 26, 2025
3c04657
Merge branch 'main' into feat(eslint-plugin)---no-useless-default-ass…
JoshuaKGoldberg Nov 28, 2025
071c2ef
Merge branch 'main' into feat(eslint-plugin)---no-useless-default-ass…
ulrichstark Dec 1, 2025
9334493
remove unnecessary type assertion
ulrichstark Dec 1, 2025
be81a7f
check for string index type
ulrichstark Dec 1, 2025
ed0011c
support compiler option noUncheckedIndexedAccess properly
ulrichstark Dec 1, 2025
026fd7f
also support noUncheckedIndexedAccess for records/mapped types
ulrichstark Dec 2, 2025
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
---
description: 'Disallow default values that will never be used.'
---

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

> 🛑 This file is source code, not the primary documentation location! 🛑
>
> See **https://typescript-eslint.io/rules/no-useless-default-assignment** for documentation.

[Default parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters) and [default values](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value) are only used if the parameter or property is `undefined`.
That can happen when a value is missing, or when one is provided and set to `undefined`.
If a non-`undefined` value is guaranteed to be provided, then there is no need to define a default.

## Examples

<Tabs>
<TabItem value="❌ Incorrect">

```ts
function Bar({ foo = '' }: { foo: string }) {
return foo;
}

const { foo = '' } = { foo: 'bar' };

const [foo = ''] = ['bar'];

[1, 2, 3].map((a = 42) => a + 1);
```

</TabItem>
<TabItem value="✅ Correct">

```ts
function Bar({ foo = '' }: { foo?: string }) {
return foo;
}

const { foo = '' } = { foo: undefined };

const [foo = ''] = [undefined];

[1, 2, 3, undefined].map((a = 42) => a + 1);
```

</TabItem>
</Tabs>

## When Not To Use It

If you use default values defensively against runtime values that bypass type checking, or for documentation purposes, you may want to disable this rule.
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/configs/eslintrc/all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ export = {
'@typescript-eslint/no-use-before-define': 'error',
'no-useless-constructor': 'off',
'@typescript-eslint/no-useless-constructor': 'error',
'@typescript-eslint/no-useless-default-assignment': 'error',
'@typescript-eslint/no-useless-empty-export': 'error',
'@typescript-eslint/no-wrapper-object-types': 'error',
'@typescript-eslint/non-nullable-type-assertion-style': 'error',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export = {
'@typescript-eslint/no-unsafe-return': 'off',
'@typescript-eslint/no-unsafe-type-assertion': 'off',
'@typescript-eslint/no-unsafe-unary-minus': 'off',
'@typescript-eslint/no-useless-default-assignment': 'off',
'@typescript-eslint/non-nullable-type-assertion-style': 'off',
'@typescript-eslint/only-throw-error': 'off',
'@typescript-eslint/prefer-destructuring': 'off',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export = {
'@typescript-eslint/no-unsafe-member-access': 'error',
'@typescript-eslint/no-unsafe-return': 'error',
'@typescript-eslint/no-unsafe-unary-minus': 'error',
'@typescript-eslint/no-useless-default-assignment': 'error',
'no-throw-literal': 'off',
'@typescript-eslint/only-throw-error': 'error',
'prefer-promise-reject-errors': 'off',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export = {
'@typescript-eslint/no-unused-vars': 'error',
'no-useless-constructor': 'off',
'@typescript-eslint/no-useless-constructor': 'error',
'@typescript-eslint/no-useless-default-assignment': 'error',
'@typescript-eslint/no-wrapper-object-types': 'error',
'no-throw-literal': 'off',
'@typescript-eslint/only-throw-error': 'error',
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/configs/flat/all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ export default (
'@typescript-eslint/no-use-before-define': 'error',
'no-useless-constructor': 'off',
'@typescript-eslint/no-useless-constructor': 'error',
'@typescript-eslint/no-useless-default-assignment': 'error',
'@typescript-eslint/no-useless-empty-export': 'error',
'@typescript-eslint/no-wrapper-object-types': 'error',
'@typescript-eslint/non-nullable-type-assertion-style': 'error',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export default (
'@typescript-eslint/no-unsafe-return': 'off',
'@typescript-eslint/no-unsafe-type-assertion': 'off',
'@typescript-eslint/no-unsafe-unary-minus': 'off',
'@typescript-eslint/no-useless-default-assignment': 'off',
'@typescript-eslint/non-nullable-type-assertion-style': 'off',
'@typescript-eslint/only-throw-error': 'off',
'@typescript-eslint/prefer-destructuring': 'off',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export default (
'@typescript-eslint/no-unsafe-member-access': 'error',
'@typescript-eslint/no-unsafe-return': 'error',
'@typescript-eslint/no-unsafe-unary-minus': 'error',
'@typescript-eslint/no-useless-default-assignment': 'error',
'no-throw-literal': 'off',
'@typescript-eslint/only-throw-error': 'error',
'prefer-promise-reject-errors': 'off',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ export default (
'@typescript-eslint/no-unused-vars': 'error',
'no-useless-constructor': 'off',
'@typescript-eslint/no-useless-constructor': 'error',
'@typescript-eslint/no-useless-default-assignment': 'error',
'@typescript-eslint/no-wrapper-object-types': 'error',
'no-throw-literal': 'off',
'@typescript-eslint/only-throw-error': 'error',
Expand Down
2 changes: 2 additions & 0 deletions packages/eslint-plugin/src/rules/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ import noUnusedPrivateClassMembers from './no-unused-private-class-members';
import noUnusedVars from './no-unused-vars';
import noUseBeforeDefine from './no-use-before-define';
import noUselessConstructor from './no-useless-constructor';
import noUselessDefaultAssignment from './no-useless-default-assignment';
import noUselessEmptyExport from './no-useless-empty-export';
import noVarRequires from './no-var-requires';
import noWrapperObjectTypes from './no-wrapper-object-types';
Expand Down Expand Up @@ -227,6 +228,7 @@ const rules = {
'no-unused-vars': noUnusedVars,
'no-use-before-define': noUseBeforeDefine,
'no-useless-constructor': noUselessConstructor,
'no-useless-default-assignment': noUselessDefaultAssignment,
'no-useless-empty-export': noUselessEmptyExport,
'no-var-requires': noVarRequires,
'no-wrapper-object-types': noWrapperObjectTypes,
Expand Down
263 changes: 263 additions & 0 deletions packages/eslint-plugin/src/rules/no-useless-default-assignment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,263 @@
import type { TSESTree } from '@typescript-eslint/utils';

import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import * as tsutils from 'ts-api-utils';
import * as ts from 'typescript';

import {
createRule,
getParserServices,
isFunction,
isTypeAnyType,
isTypeFlagSet,
isTypeUnknownType,
nullThrows,
NullThrowsReasons,
} from '../util';

type MessageId = 'uselessDefaultAssignment' | 'uselessUndefined';

export default createRule<[], MessageId>({
name: 'no-useless-default-assignment',
meta: {
type: 'suggestion',
docs: {
description: 'Disallow default values that will never be used',
recommended: 'strict',
requiresTypeChecking: true,
},
fixable: 'code',
messages: {
uselessDefaultAssignment:
'Default value is useless because the {{ type }} is not optional.',
uselessUndefined:
'Default value is useless because it is undefined. Optional {{ type }}s are already undefined by default.',
},
schema: [],
},
defaultOptions: [],
create(context) {
const services = getParserServices(context);
const checker = services.program.getTypeChecker();
const compilerOptions = services.program.getCompilerOptions();
const isNoUncheckedIndexedAccess = tsutils.isCompilerOptionEnabled(
compilerOptions,
'noUncheckedIndexedAccess',
);

function canBeUndefined(type: ts.Type): boolean {
if (isTypeAnyType(type) || isTypeUnknownType(type)) {
return true;
}
return tsutils
.unionConstituents(type)
.some(part => isTypeFlagSet(part, ts.TypeFlags.Undefined));
}

function getPropertyType(
objectType: ts.Type,
propertyName: string,
): ts.Type | null {
const symbol = objectType.getProperty(propertyName);
if (!symbol) {
if (isNoUncheckedIndexedAccess) {
return null;
}
return objectType.getStringIndexType() ?? null;
}
return checker.getTypeOfSymbol(symbol);
}

function getArrayElementType(
arrayType: ts.Type,
elementIndex: number,
): ts.Type | null {
if (checker.isTupleType(arrayType)) {
const tupleArgs = checker.getTypeArguments(arrayType);
if (elementIndex < tupleArgs.length) {
return tupleArgs[elementIndex];
}
}

if (isNoUncheckedIndexedAccess) {
return null;
}

return arrayType.getNumberIndexType() ?? null;
}

function checkAssignmentPattern(node: TSESTree.AssignmentPattern): void {
if (
node.right.type === AST_NODE_TYPES.Identifier &&
node.right.name === 'undefined'
) {
const type =
node.parent.type === AST_NODE_TYPES.Property ||
node.parent.type === AST_NODE_TYPES.ArrayPattern
? 'property'
: 'parameter';
reportUselessDefault(node, type, 'uselessUndefined');
return;
}

const parent = node.parent;

if (
parent.type === AST_NODE_TYPES.ArrowFunctionExpression ||
parent.type === AST_NODE_TYPES.FunctionExpression
) {
const paramIndex = parent.params.indexOf(node);
if (paramIndex !== -1) {
const tsFunc = services.esTreeNodeToTSNodeMap.get(parent);
if (ts.isFunctionLike(tsFunc)) {
const contextualType = checker.getContextualType(
tsFunc as ts.Expression,
);
if (!contextualType) {
return;
}

const signatures = contextualType.getCallSignatures();
const params = signatures[0].getParameters();
if (paramIndex < params.length) {
const paramSymbol = params[paramIndex];
if ((paramSymbol.flags & ts.SymbolFlags.Optional) === 0) {
const paramType = checker.getTypeOfSymbol(paramSymbol);
if (!canBeUndefined(paramType)) {
reportUselessDefault(
node,
'parameter',
'uselessDefaultAssignment',
);
}
}
}
}
}
return;
}

if (parent.type === AST_NODE_TYPES.Property) {
const propertyType = getTypeOfProperty(parent);
if (!propertyType) {
return;
}

if (!canBeUndefined(propertyType)) {
reportUselessDefault(node, 'property', 'uselessDefaultAssignment');
}
} else if (parent.type === AST_NODE_TYPES.ArrayPattern) {
const sourceType = getSourceTypeForPattern(parent);
if (!sourceType) {
return;
}

const elementIndex = parent.elements.indexOf(node);
const elementType = getArrayElementType(sourceType, elementIndex);
if (!elementType) {
return;
}

if (!canBeUndefined(elementType)) {
reportUselessDefault(node, 'property', 'uselessDefaultAssignment');
}
}
}

function getTypeOfProperty(node: TSESTree.Property): ts.Type | null {
const objectPattern = node.parent as TSESTree.ObjectPattern;
const sourceType = getSourceTypeForPattern(objectPattern);
if (!sourceType) {
return null;
}

const propertyName = getPropertyName(node.key);
if (!propertyName) {
return null;
}

return getPropertyType(sourceType, propertyName);
}

function getSourceTypeForPattern(pattern: TSESTree.Node): ts.Type | null {
const parent = nullThrows(
pattern.parent,
NullThrowsReasons.MissingParent,
);

if (parent.type === AST_NODE_TYPES.VariableDeclarator && parent.init) {
const tsNode = services.esTreeNodeToTSNodeMap.get(parent.init);
return checker.getTypeAtLocation(tsNode);
}

if (isFunction(parent)) {
const paramIndex = parent.params.indexOf(pattern as TSESTree.Parameter);
const tsFunc = services.esTreeNodeToTSNodeMap.get(parent);
const signature = nullThrows(
checker.getSignatureFromDeclaration(tsFunc),
NullThrowsReasons.MissingToken('signature', 'function'),
);
const params = signature.getParameters();
return checker.getTypeOfSymbol(params[paramIndex]);
}

if (parent.type === AST_NODE_TYPES.AssignmentPattern) {
return getSourceTypeForPattern(parent);
}

if (parent.type === AST_NODE_TYPES.Property) {
return getTypeOfProperty(parent);
}

if (parent.type === AST_NODE_TYPES.ArrayPattern) {
const arrayPattern = parent;
const arrayType = getSourceTypeForPattern(arrayPattern);
if (!arrayType) {
return null;
}
const elementIndex = arrayPattern.elements.indexOf(
pattern as TSESTree.DestructuringPattern,
);
return getArrayElementType(arrayType, elementIndex);
}

return null;
}

function getPropertyName(
key: TSESTree.Expression | TSESTree.PrivateIdentifier,
): string | null {
switch (key.type) {
case AST_NODE_TYPES.Identifier:
return key.name;
case AST_NODE_TYPES.Literal:
return String(key.value);
default:
return null;
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Non-Actionable] I'm surprised a utility doesn't already exist for this - but I couldn't find one.

  • getStaticValue: doesn't handle identifiers
  • getStringIfConstant: doesn't handle identifiers (it's a small wrapper around getStaticStringValue)
  • getStaticStringValue: didn't handle identifiers properly

Not requesting changes, just noting - maybe I missed one?


function reportUselessDefault(
node: TSESTree.AssignmentPattern,
type: 'parameter' | 'property',
messageId: MessageId,
): void {
context.report({
node: node.right,
messageId,
data: { type },
fix(fixer) {
// Remove from before the = to the end of the default value
// Find the start position (including whitespace before =)
const start = node.left.range[1];
const end = node.range[1];
return fixer.removeRange([start, end]);
},
});
}

return {
AssignmentPattern: checkAssignmentPattern,
};
},
});
Loading
Loading