From aae59b93e6511db43627ba1d13674d5e391d7212 Mon Sep 17 00:00:00 2001 From: David Baker Date: Mon, 9 Oct 2023 14:34:36 +0100 Subject: [PATCH] Re-write the rule about casting to be clearer (#26317) This is the proposal from the comments on https://github.com/vector-im/element-web/pull/26220 (so effectively an alternative to that PR, if you like). --- code_style.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/code_style.md b/code_style.md index c1c9beda78..0462f3a4a9 100644 --- a/code_style.md +++ b/code_style.md @@ -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) && ...; + 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 - // but *not*: - const isRealUser = userId && ...; // invalid implicit cast + 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.