Skip to content

[@typescript-eslint/no-unnecessary-condition] Nullable object can still fail the linter #1897

Closed
@astorije

Description

@astorije

Repro

rules:
  '@typescript-eslint/no-unnecessary-condition':
    - error
    - ignoreRhs: true
      checkArrayPredicates: true
import React, { FunctionComponent } from 'react';

export const Foo: FunctionComponent<{ opt?: string; req: string }> = props => (
  <>{props.children || props.req || props.opt}</>
);

export const Bar: FunctionComponent<{ opt?: string; req: string }> = props => (
  <>{props.req || props.opt}</>
);

export const Baz: FunctionComponent<{ req: string }> = props => (
  <>{props.children || props.req}</>
);

Expected Result

Per the @types/react types, children is optional:

type PropsWithChildren<P> = P & { children?: ReactNode };

Because of this, I would expect all examples above to pass the rule.

Actual Result

For a reason I do not understand, the first example (Foo) fails the linter:

     Unnecessary conditional, value is always truthy

     src/Foobar.tsx:4:6
     2 |
     3 | export const Foo: FunctionComponent<{ opt?: string; req: string }> = props => (
   > 4 |   <>{props.children || props.req || props.opt}</>
       |      ^
     5 | );

But we know from the types that props.children is not always truthy.

Additionally:

  • If the issue is indeed that props.children is always truthy, Baz should fail
  • I was wondering if the issue was because props.req is non-nullable (but '' is still falsy) but Bar doesn't fail either

I can't seem to find another combination that makes the linter scream, unless I'm missing something.

Additional Info

Apologies if this has already been reported. I went through existing tickets, opened and closed, and didn't find something similar.

Versions

package version
@typescript-eslint/eslint-plugin 2.27.0
@typescript-eslint/parser 2.27.0
TypeScript 3.8.3
ESLint 6.8.0
node 12.14.0
yarn 1.22.4

Metadata

Metadata

Assignees

No one assigned

    Labels

    package: eslint-pluginIssues related to @typescript-eslint/eslint-pluginstalePRs or Issues that are at risk of being or have been closed due to inactivity for a prolonged period

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions