Skip to content

Commit

Permalink
Re-write the rule about casting to be clearer (#26317)
Browse files Browse the repository at this point in the history
This is the proposal from the comments on #26220
(so effectively an alternative to that PR, if you like).
  • Loading branch information
dbkr authored Oct 9, 2023
1 parent d74186d commit aae59b9
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions code_style.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,15 +113,17 @@ Unless otherwise specified, the following applies to all code:
}
```

14. Explicitly cast to a boolean, rather than relying on implicit truthiness of non-boolean values:
14. If a variable's type should be boolean, make sure it really is one.

```typescript
const isRealUser = !!userId && ...;
// ... or ...
const isRealUser = Boolean(userId) && ...;
// but *not*:
const isRealUser = userId && ...; // invalid implicit cast
const isRealUser = !!userId && ...; // good
const isRealUser = Boolean(userId) && Boolean(userName); // also good
const isRealUser = Boolean(userId) && isReal; // also good (where isReal is another boolean variable)
const isRealUser = Boolean(userId && userName); // also fine
const isRealUser = Boolean(userId || userName); // good: same as &&
const isRealUser = userId && ...; // bad: isRealUser is userId's type, not a boolean
if (userId) // fine: userId is evaluated for truthiness, not stored as a boolean
```

15. Use `switch` statements when checking against more than a few enum-like values.
Expand Down

0 comments on commit aae59b9

Please sign in to comment.