Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 3e5f858

Browse files
authored
fix(eslint-plugin): [no-unnecessary-condition] allow nullish coalescing for naked type parameter (typescript-eslint#6910)
* fix(eslint-plugin): [no-unnecessary-condition] allow nullish coalescing for naked type parameter * add tests
1 parent 276c17b commit 3e5f858

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

packages/eslint-plugin/src/rules/no-unnecessary-condition.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -263,8 +263,14 @@ export default createRule<Options, MessageId>({
263263

264264
function checkNodeForNullish(node: TSESTree.Expression): void {
265265
const type = getNodeType(node);
266-
// Conditional is always necessary if it involves `any` or `unknown`
267-
if (isTypeAnyType(type) || isTypeUnknownType(type)) {
266+
267+
// Conditional is always necessary if it involves `any`, `unknown` or a naked type parameter
268+
if (
269+
isTypeFlagSet(
270+
type,
271+
ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.TypeParameter,
272+
)
273+
) {
268274
return;
269275
}
270276

packages/eslint-plugin/tests/rules/no-unnecessary-condition.test.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,16 @@ function test(a: string | null | undefined) {
280280
`
281281
function test(a: unknown) {
282282
return a ?? 'default';
283+
}
284+
`,
285+
`
286+
function test<T>(a: T) {
287+
return a ?? 'default';
288+
}
289+
`,
290+
`
291+
function test<T extends string | null>(a: T) {
292+
return a ?? 'default';
283293
}
284294
`,
285295
// Indexing cases
@@ -827,6 +837,14 @@ function test(a: string) {
827837
code: `
828838
function test(a: string | false) {
829839
return a ?? 'default';
840+
}
841+
`,
842+
errors: [ruleError(3, 10, 'neverNullish')],
843+
},
844+
{
845+
code: `
846+
function test<T extends string>(a: T) {
847+
return a ?? 'default';
830848
}
831849
`,
832850
errors: [ruleError(3, 10, 'neverNullish')],
@@ -858,6 +876,14 @@ function test(a: null[]) {
858876
},
859877
{
860878
code: `
879+
function test<T extends null>(a: T) {
880+
return a ?? 'default';
881+
}
882+
`,
883+
errors: [ruleError(3, 10, 'alwaysNullish')],
884+
},
885+
{
886+
code: `
861887
function test(a: never) {
862888
return a ?? 'default';
863889
}

0 commit comments

Comments
 (0)