Skip to content

Async functions that return booleans: un-awaited function calls are not flagged as always being truthy #41716

Closed
@AleksandrHovhannisyan

Description

@AleksandrHovhannisyan

TypeScript Version: 4.1.2

Search Terms: async functions, booleans, async return values, async booleans

Code

const isBroken = async () => false;

if (isBroken()) {
  console.log('asd')
}

Expected behavior:

TypeScript should warn you that the expression evaluated in the if statement will always be true. See my explanation of this behavior here.

If you remove the function call and just do if (isBroken), TypeScript will rightly complain that the expression will always return true:

image

That's because functions are truthy objects, so when they're coerced to booleans, they're always true. Likewise, an async function returns a Promise object implicitly, and that's always truthy. So TypeScript should really flag that as an error, but it doesn't.

Actual behavior:

TypeScript does not complain. The code can lead to bugs, but it's something that can be checked statically before the code is ever compiled.

Playground Link:

https://www.typescriptlang.org/play?#code/MYewdgzgLgBAlhAQgJxAawKZhgXhgQwgE8xgYAKASlwD4YAzfAGwgwG4AoDueihFdFmoBvDjBihIIJhgB0TEAHNyAckIATFZQ4BfIA
Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions