Skip to content

Commit

Permalink
fix(eslint-plugin): [no-unnecessary-condition] allow nullish coalesci…
Browse files Browse the repository at this point in the history
…ng for naked type parameter (#6910)

* fix(eslint-plugin): [no-unnecessary-condition] allow nullish coalescing for naked type parameter

* add tests
  • Loading branch information
dora1998 committed Apr 17, 2023
1 parent 276c17b commit 3e5f858
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
10 changes: 8 additions & 2 deletions packages/eslint-plugin/src/rules/no-unnecessary-condition.ts
Expand Up @@ -263,8 +263,14 @@ export default createRule<Options, MessageId>({

function checkNodeForNullish(node: TSESTree.Expression): void {
const type = getNodeType(node);
// Conditional is always necessary if it involves `any` or `unknown`
if (isTypeAnyType(type) || isTypeUnknownType(type)) {

// Conditional is always necessary if it involves `any`, `unknown` or a naked type parameter
if (
isTypeFlagSet(
type,
ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.TypeParameter,
)
) {
return;
}

Expand Down
Expand Up @@ -280,6 +280,16 @@ function test(a: string | null | undefined) {
`
function test(a: unknown) {
return a ?? 'default';
}
`,
`
function test<T>(a: T) {
return a ?? 'default';
}
`,
`
function test<T extends string | null>(a: T) {
return a ?? 'default';
}
`,
// Indexing cases
Expand Down Expand Up @@ -827,6 +837,14 @@ function test(a: string) {
code: `
function test(a: string | false) {
return a ?? 'default';
}
`,
errors: [ruleError(3, 10, 'neverNullish')],
},
{
code: `
function test<T extends string>(a: T) {
return a ?? 'default';
}
`,
errors: [ruleError(3, 10, 'neverNullish')],
Expand Down Expand Up @@ -858,6 +876,14 @@ function test(a: null[]) {
},
{
code: `
function test<T extends null>(a: T) {
return a ?? 'default';
}
`,
errors: [ruleError(3, 10, 'alwaysNullish')],
},
{
code: `
function test(a: never) {
return a ?? 'default';
}
Expand Down

0 comments on commit 3e5f858

Please sign in to comment.