Skip to content

Docs: [no-unnecessary-condition] mention subtleties of primitives' assignability #10970

@kirkwaiblinger

Description

@kirkwaiblinger

Before You File a Documentation Request Please Confirm You Have Done The Following...

Suggested Changes

I'd like to add a section that briefly alerts users to the nuances around primitives being assignable to object types, causing sort-of-false-positives with no-unnecessary-condition's truthiness checks.

I'd like to mention:

  • "object types" are just "things with properties", not objects (a superset of no-empty-object-type shenanigans)

    function foo(x: { toString: Function }) {
       if (x) { // reported by no-unnecessary-condition as always-truthy
       }
    }
    
    foo(false); 
    foo(true);
    foo({});
  • object can easily contain primitives at runtime, without typical obviously unsafe TS patterns.

    function foo(o: object) {
      if (o) { // reported by no-unnecessary-condition as always-truthy
      }
    }
    
    foo(false); // TS error.
    
    const lol: {} = false;
    foo(lol); // but this is allowed by TS.

As said, I think this should be brief, just to alert users to possibly-faulty common assumptions about the type system, and then punt deeper dive to microsoft/TypeScript#60582 (comment) or any other good references. The main goal is really to convey think closely about your application before "fixing" a truthiness report, since the condition may actually be necessary, despite what the types appear to be indicate.

Affected URL(s)

https://main--typescript-eslint.netlify.app/rules/no-unnecessary-condition#limitations

Additional Info

Relates to #10378, which may eventually change some of this behavior. But regardless of rule behavior change on our side, it's valuable for users to know that primitives may be lurking places they didn't expect.

Metadata

Metadata

Assignees

No one assigned

    Labels

    accepting prsGo ahead, send a pull request that resolves this issuedocumentationDocumentation ("docs") that needs adding/updating

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions