Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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) {
Copy link
Member

Choose a reason for hiding this comment

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

[Testing] The cases of T extends 'a' (always truthy) and T extends 'a' | null (still needing ??) seem to work, but aren't explicitly covered for ?? cases. Could you add in a couple more unit tests along those lines please?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Oh sorry, I added them!
I also added a alwaysNullish case 😄

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