Skip to content

Don't allow applying the ! operator to uncalled functionsΒ #61607

Closed as not planned
@DonaldDuck313

Description

@DonaldDuck313

πŸ” Search Terms

This condition will always return true since this function is always defined. Did you mean to call it instead? TS2774

βœ… Viability Checklist

⭐ Suggestion

If someFunction is a function, if(someFunction){...} gives error TS2774 because foo is always truthy and was probably intended to be called. However, !someFunction is allowed, always returning false. I suggest that !someFunction should be an error in the same way as if(someFunction){...}.

Depending on how strict you are about backwards compatibility, this could be an option that's disabled by default, because technically it would be a breaking change (since !someFunction currently compiles but wouldn't compile with my suggestion). However, in practice, I can't think of any code that works as intended and that would be broken by this suggestion, since I don't see why anyone intentionally writing !someFunction wouldn't just use the literal false instead.

πŸ“ƒ Motivating Example

declare function someFunction(): boolean;

if(someFunction){    //Oops, should be someFunction(), TypeScript helpfully warns me about this
    //Do something
}

if(!someFunction){    //No error, the if block will never be executed which can lead to bugs at runtime
    //Do something else
}

πŸ’» Use Cases

  1. What do you want to use this for?

    To get an error when it's obvious that I forgot to call a function (the same reason TS2774 already exists).

  2. What shortcomings exist with current approaches?

    I have to run the code, see that something is wrong, and debug it. In the best of cases this is unnecessarily time consuming, in the worst of cases I won't notice that anything is wrong and the bug will go into production code.

  3. What workarounds are you using in the meantime?

    Runtime debugging, I guess I don't have much choice.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions