|
| 1 | +# Boolean |
| 2 | + |
| 3 | +The type of boolean in TypeScript is `boolean`. |
| 4 | +It also have boolean literal types `true` and `false` |
| 5 | + |
| 6 | +--- |
| 7 | + |
| 8 | +Predicate functions **should** return `boolean`. |
| 9 | + |
| 10 | +```ts |
| 11 | +// bad |
| 12 | +function hasValue(value: any) { |
| 13 | + return value |
| 14 | +} |
| 15 | + |
| 16 | +// good |
| 17 | +function hasValue(value: any) { |
| 18 | + return value !== undefined |
| 19 | +} |
| 20 | +``` |
| 21 | + |
| 22 | +> Why? |
| 23 | +
|
| 24 | +Relying on implicit conversion is dangerous. |
| 25 | +Always be explicit. |
| 26 | + |
| 27 | +```ts |
| 28 | +hasValue(0) ? true : false // false |
| 29 | +hasValue(false) ? true : false // false |
| 30 | +hasValue('') ? true : false // false |
| 31 | +hasValue(Symbol()) ? true : false // false |
| 32 | +hasValue(Infinity) ? true : false // false |
| 33 | +// but |
| 34 | +new Boolean(Infinity) // true !! |
| 35 | +``` |
| 36 | + |
| 37 | +--- |
| 38 | + |
| 39 | +When converting value to boolean, you **should** use double not (`!!`) operator. |
| 40 | + |
| 41 | +```ts |
| 42 | +const value = false |
| 43 | +// bad |
| 44 | +const b = new Boolean(value) |
| 45 | +if (b) { /* executed! */ } |
| 46 | + |
| 47 | +// so so |
| 48 | +const c = Boolean(value) |
| 49 | +if (c) { /* not executed */ } |
| 50 | + |
| 51 | +// good |
| 52 | +const d = !!value |
| 53 | +if (d) { /* not executed */ } |
| 54 | +``` |
| 55 | + |
| 56 | +> Why? |
| 57 | +
|
| 58 | +In 99.99999% of the time, |
| 59 | +you do not even know the existence of the boolean object wrapper `Boolean`. |
| 60 | +It is different then the `boolean` you use days in days out. |
| 61 | + |
| 62 | +So don't confuse yourself and your reader by mentioning it in your code when not necessary. |
| 63 | + |
| 64 | +## References |
| 65 | + |
| 66 | +- <https://www.typescriptlang.org/docs/handbook/basic-types.html#boolean> |
| 67 | +- <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean> |
0 commit comments