@spscommerce/eslint-config-typescript 0.0.15 → 8.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/GUIDE.md +3877 -0
  2. package/README.md +3 -3844
  3. package/dist/out-tsc/index.d.ts +3 -0
  4. package/dist/out-tsc/index.js +81 -0
  5. package/dist/out-tsc/index.js.map +1 -0
  6. package/dist/out-tsc/rules/bestPractices.d.ts +2 -0
  7. package/{lib → dist/out-tsc}/rules/bestPractices.js +6 -1
  8. package/dist/out-tsc/rules/bestPractices.js.map +1 -0
  9. package/dist/out-tsc/rules/es6.d.ts +2 -0
  10. package/{lib → dist/out-tsc}/rules/es6.js +1 -0
  11. package/dist/out-tsc/rules/es6.js.map +1 -0
  12. package/dist/out-tsc/rules/imports/helpfulWarnings.d.ts +2 -0
  13. package/{lib → dist/out-tsc}/rules/imports/helpfulWarnings.js +1 -0
  14. package/dist/out-tsc/rules/imports/helpfulWarnings.js.map +1 -0
  15. package/dist/out-tsc/rules/imports/index.d.ts +4 -0
  16. package/{lib → dist/out-tsc}/rules/imports/index.js +1 -0
  17. package/dist/out-tsc/rules/imports/index.js.map +1 -0
  18. package/dist/out-tsc/rules/imports/moduleSystems.d.ts +2 -0
  19. package/{lib → dist/out-tsc}/rules/imports/moduleSystems.js +1 -0
  20. package/dist/out-tsc/rules/imports/moduleSystems.js.map +1 -0
  21. package/dist/out-tsc/rules/imports/staticAnalysis.d.ts +2 -0
  22. package/{lib → dist/out-tsc}/rules/imports/staticAnalysis.js +1 -0
  23. package/dist/out-tsc/rules/imports/staticAnalysis.js.map +1 -0
  24. package/dist/out-tsc/rules/imports/styleGuide.d.ts +2 -0
  25. package/{lib → dist/out-tsc}/rules/imports/styleGuide.js +1 -0
  26. package/dist/out-tsc/rules/imports/styleGuide.js.map +1 -0
  27. package/dist/out-tsc/rules/possibleErrors.d.ts +2 -0
  28. package/{lib → dist/out-tsc}/rules/possibleErrors.js +1 -0
  29. package/dist/out-tsc/rules/possibleErrors.js.map +1 -0
  30. package/dist/out-tsc/rules/strictMode.d.ts +2 -0
  31. package/{lib → dist/out-tsc}/rules/strictMode.js +1 -0
  32. package/dist/out-tsc/rules/strictMode.js.map +1 -0
  33. package/dist/out-tsc/rules/stylisticIssues.d.ts +2 -0
  34. package/{lib → dist/out-tsc}/rules/stylisticIssues.js +1 -0
  35. package/dist/out-tsc/rules/stylisticIssues.js.map +1 -0
  36. package/dist/out-tsc/rules/typescript.d.ts +2 -0
  37. package/{lib → dist/out-tsc}/rules/typescript.js +1 -0
  38. package/dist/out-tsc/rules/typescript.js.map +1 -0
  39. package/dist/out-tsc/rules/variables.d.ts +2 -0
  40. package/{lib → dist/out-tsc}/rules/variables.js +1 -0
  41. package/dist/out-tsc/rules/variables.js.map +1 -0
  42. package/package.json +3 -2
  43. package/tsconfig.json +14 -8
  44. package/LICENSE.md +0 -21
  45. package/lib/index.js +0 -45
package/GUIDE.md ADDED
@@ -0,0 +1,3877 @@
1
+ # @spscommerce/eslint-config-typescript
2
+
3
+ > An ESLint@8 config that attempts to enforce SPS Commerce's typescript style guide (see below for the style guide contents)
4
+
5
+ ## About this package
6
+
7
+ ### History
8
+
9
+ This package previously lived in the SPSCommerce/typescript repo. That repo was forked from AirBnB's style guide and represents careful work in 2021 by the Frontend Architecture Working Group to select rules that are valuable. The goal was for this package to encourage a consistent developer experience.
10
+
11
+ The reality is that this ESLint@8 config has mixed acceptance across teams and repositories. Additionally, the ESLint@9 breaking changes represent a large shift with somewhat challenging backwards compatibility. This means we need to rethink how this package should be updated (or more likely, a new one created) for that new ecosystem and how it interacts with Prettier. Prettier is now a popular code formatter that is quite opinionated in ways that are at odds with our lint rules.
12
+
13
+ At the time of writing the latest ESLint@8 versions of this config require a user to not upgrade past the following dependencies:
14
+
15
+ ```
16
+ "@stylistic/eslint-plugin": "^3.1.0",
17
+ "eslint": "^8.57.1",
18
+ "eslint-import-resolver-typescript": "^3.10.1",
19
+ ```
20
+
21
+ ### Version jump
22
+
23
+ Historically this package was published manually and so it never acheived a v1 until it was moved to the SPSCommerce/sps-js-shared repo at which point it jumped to version 8.x to sync up with services, slasher and utils.
24
+
25
+ ### Future
26
+
27
+ At the time of writing in September 2025 the FAWG do not have an ESLint@v9 config (though some applications have their own). The ESLint@8 package is mostly complete as we cannot upgrade several of the peer dependencies without breaking existing users of the ESLint@8 config.
28
+
29
+ We are investigating the possibility of offering several v9 configs (or at least offering comprehensive examples). Whatever we do we'll need to accomodate various types of packages (browser, node, typescript, jsx, etc) and also find out how to work with prettier.
30
+
31
+
32
+ ## SPS Commerce TypeScript Style Guide
33
+
34
+ ## Table of Contents
35
+
36
+ 1. [Types](#types)
37
+ 1. [References](#references)
38
+ 1. [Objects](#objects)
39
+ 1. [Arrays](#arrays)
40
+ 1. [Destructuring](#destructuring)
41
+ 1. [Strings](#strings)
42
+ 1. [Promises](#promises)
43
+ 1. [Functions](#functions)
44
+ 1. [Arrow Functions](#arrow-functions)
45
+ 1. [Classes & Constructors](#classes--constructors)
46
+ 1. [Modules](#modules)
47
+ 1. [Iterators and Generators](#iterators-and-generators)
48
+ 1. [Properties](#properties)
49
+ 1. [Variables](#variables)
50
+ 1. [Comparison Operators & Equality](#comparison-operators--equality)
51
+ 1. [Blocks](#blocks)
52
+ 1. [Control Statements](#control-statements)
53
+ 1. [Comments](#comments)
54
+ 1. [Whitespace](#whitespace)
55
+ 1. [Commas](#commas)
56
+ 1. [Semicolons](#semicolons)
57
+ 1. [Type Casting & Coercion](#type-casting--coercion)
58
+ 1. [Naming Conventions](#naming-conventions)
59
+ 1. [Accessors](#accessors)
60
+ 1. [Events](#events)
61
+ 1. [Standard Library](#standard-library)
62
+ 1. [Language Proposals](#language-proposals)
63
+ 1. [Testing](#testing)
64
+ 1. [Resources](#resources)
65
+
66
+ ## Types
67
+
68
+ <a name="types--primitives"></a>
69
+ 💡 [**1.1**](#types--primitives) ‣ Primitives: When you access a primitive type you work directly on its value.
70
+
71
+ - `string`
72
+ - `number`
73
+ - `boolean`
74
+ - `null`
75
+ - `undefined`
76
+ - `symbol`
77
+ - `bigint`
78
+
79
+
80
+ ```typescript
81
+ const foo = 1;
82
+ let bar = foo;
83
+
84
+ bar = 9;
85
+
86
+ console.log(foo, bar); // => 1, 9
87
+ ```
88
+
89
+ Symbols and BigInts cannot be faithfully polyfilled, so they should not be used when targeting browsers/environments that don’t support them natively.
90
+
91
+ ---
92
+
93
+ <a name="types--complex"></a>
94
+ 💡 [**1.2**](#types--complex) ‣ Complex: When you access a complex type you work on a reference to its value.
95
+
96
+ - `object`
97
+ - `array`
98
+ - `function`
99
+
100
+
101
+ ```typescript
102
+ const foo = [1, 2];
103
+ const bar = foo;
104
+
105
+ bar[0] = 9;
106
+
107
+ console.log(foo[0], bar[0]); // => 9, 9
108
+ ```
109
+
110
+ ---
111
+
112
+ <a name="types--assertions"></a>
113
+ [**1.3**](#types--assertions) ‣ Type assertions should be written in `as` style, rather than prefix style.
114
+
115
+ <img src="../eslint.svg" height="18" align="center"/> [`@typescript-eslint/consistent-type-assertions`](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/consistent-type-assertions.md)
116
+
117
+ > Why? Because it uses angle brackets, the prefix style can be confused when generics are also in play, as well as potentially tripping up IDEs and tooling in `.tsx` files.
118
+
119
+ ```typescript
120
+ function squareIt(num: number): number {
121
+ return num ** 2;
122
+ }
123
+
124
+ const foo: string | number = 5;
125
+
126
+ // bad
127
+ console.log(squareIt(<number>foo));
128
+
129
+ // good
130
+ console.log(squareIt(foo as number));
131
+ ```
132
+
133
+ ---
134
+
135
+ <a name="types--enums"></a>
136
+ [**1.4**](#types--enums) ‣ Explicitly initialize the values of enum members.
137
+
138
+ <img src="../eslint.svg" height="18" align="center"/> [`@typescript-eslint/prefer-enum-initializers`](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/prefer-enum-initializers.md)
139
+
140
+ > Why? If you allow member values to be inferred, then adding a new member can result in the values of pre-existing members changing. This can potentially introduce bugs.
141
+
142
+ ```typescript
143
+ // bad
144
+ enum Status {
145
+ Pending,
146
+ Complete,
147
+ }
148
+
149
+ // good
150
+ enum Status {
151
+ Pending = "PENDING",
152
+ Complete = "COMPLETE",
153
+ }
154
+ ```
155
+
156
+ **[⬆ back to top](#table-of-contents)**
157
+
158
+
159
+ ## References
160
+
161
+ <a name="references--prefer-const"></a>
162
+ [**2.1**](#references--prefer-const) ‣ Use `const` for all of your references; avoid using `var`.
163
+
164
+ <img src="../eslint.svg" height="18" align="center"/> [`prefer-const`](https://eslint.org/docs/rules/prefer-const.html), [`no-const-assign`](https://eslint.org/docs/rules/no-const-assign.html)
165
+
166
+ > Why? This ensures that you can’t reassign your references, which can lead to bugs and difficult to comprehend code.
167
+
168
+ ```typescript
169
+ // bad
170
+ var a = 1;
171
+ var b = 2;
172
+
173
+ // good
174
+ const a = 1;
175
+ const b = 2;
176
+ ```
177
+
178
+ ---
179
+
180
+ <a name="references--disallow-var"></a>
181
+ [**2.2**](#references--disallow-var) ‣ If you must reassign references, use `let` instead of `var`.
182
+
183
+ <img src="../eslint.svg" height="18" align="center"/> [`no-var`](https://eslint.org/docs/rules/no-var.html)
184
+
185
+ > Why? `let` is block-scoped rather than function-scoped like `var`.
186
+
187
+ ```typescript
188
+ // bad
189
+ var count = 1;
190
+ if (true) {
191
+ count += 1;
192
+ }
193
+
194
+ // good, use the let.
195
+ let count = 1;
196
+ if (true) {
197
+ count += 1;
198
+ }
199
+ ```
200
+
201
+ ---
202
+
203
+ <a name="references--block-scope"></a>
204
+ 💡 [**2.3**](#references--block-scope) ‣ Note that both `let` and `const` are block-scoped, whereas `var` is function-scoped.
205
+
206
+ ```typescript
207
+ // const and let only exist in the blocks they are defined in.
208
+ {
209
+ let a = 1;
210
+ const b = 1;
211
+ var c = 1;
212
+ }
213
+ console.log(a); // ReferenceError
214
+ console.log(b); // ReferenceError
215
+ console.log(c); // Prints 1
216
+ ```
217
+
218
+ In the above code, you can see that referencing `a` and `b` will produce a ReferenceError, while `c` contains the number. This is because `a` and `b` are block scoped, while `c` is scoped to the containing function.
219
+
220
+ **[⬆ back to top](#table-of-contents)**
221
+
222
+ ## Objects
223
+
224
+ <a name="objects--no-new"></a>
225
+ [**3.1**](#objects--no-new) ‣ Use the literal syntax for object creation.
226
+
227
+ <img src="../eslint.svg" height="18" align="center"/> [`no-new-object`](https://eslint.org/docs/rules/no-new-object.html)
228
+
229
+ ```typescript
230
+ // bad
231
+ const item = new Object();
232
+
233
+ // good
234
+ const item = {};
235
+ ```
236
+
237
+ ---
238
+
239
+ <a name="es6-computed-properties"></a>
240
+ [**3.2**](#es6-computed-properties) ‣ Use computed property names when creating objects with dynamic property names.
241
+
242
+ > Why? They allow you to define all the properties of an object in one place.
243
+
244
+ ```typescript
245
+ function getKey(k: string) {
246
+ return `a key named ${k}`;
247
+ }
248
+
249
+ // bad
250
+ const obj = {
251
+ id: 5,
252
+ name: 'San Francisco',
253
+ };
254
+ obj[getKey('enabled')] = true;
255
+
256
+ // good
257
+ const obj = {
258
+ id: 5,
259
+ name: 'San Francisco',
260
+ [getKey('enabled')]: true,
261
+ };
262
+ ```
263
+
264
+ ---
265
+
266
+ <a name="es6-object-shorthand"></a>
267
+ [**3.3**](#es6-object-shorthand) ‣ Use object method shorthand.
268
+
269
+ <img src="../eslint.svg" height="18" align="center"/> [`object-shorthand`](https://eslint.org/docs/rules/object-shorthand.html)
270
+
271
+ ```typescript
272
+ // bad
273
+ const atom = {
274
+ value: 1,
275
+
276
+ addValue: function (value: number) {
277
+ return atom.value + value;
278
+ },
279
+ };
280
+
281
+ // good
282
+ const atom = {
283
+ value: 1,
284
+
285
+ addValue(value: number) {
286
+ return atom.value + value;
287
+ },
288
+ };
289
+ ```
290
+
291
+ ---
292
+
293
+ <a name="es6-object-concise"></a>
294
+ [**3.4**](#es6-object-concise) ‣ Use property value shorthand.
295
+
296
+ <img src="../eslint.svg" height="18" align="center"/> [`object-shorthand`](https://eslint.org/docs/rules/object-shorthand.html)
297
+
298
+ > Why? It is shorter and descriptive.
299
+
300
+ ```typescript
301
+ const lukeSkywalker = 'Luke Skywalker';
302
+
303
+ // bad
304
+ const obj = {
305
+ lukeSkywalker: lukeSkywalker,
306
+ };
307
+
308
+ // good
309
+ const obj = {
310
+ lukeSkywalker,
311
+ };
312
+ ```
313
+
314
+ ---
315
+
316
+ <a name="objects--quoted-props"></a>
317
+ [**3.5**](#objects--quoted-props) ‣ Only quote properties that are invalid identifiers.
318
+
319
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
320
+
321
+ <img src="../eslint.svg" height="18" align="center"/> [`quote-props`](https://eslint.org/docs/rules/quote-props.html)
322
+
323
+ > Why? In general we consider it subjectively easier to read. It improves syntax highlighting, and is also more easily optimized by many JS engines.
324
+
325
+ ```typescript
326
+ // bad
327
+ const bad = {
328
+ 'foo': 3,
329
+ 'bar': 4,
330
+ 'data-blah': 5,
331
+ };
332
+
333
+ // good
334
+ const good = {
335
+ foo: 3,
336
+ bar: 4,
337
+ 'data-blah': 5,
338
+ };
339
+ ```
340
+
341
+ ---
342
+
343
+ <a name="objects--rest-spread"></a>
344
+ [**3.6**](#objects--rest-spread) ‣ Prefer the object spread syntax over [`Object.assign`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) to shallow-copy objects. Use the object rest operator to get a new object with certain properties omitted.
345
+
346
+ <img src="../eslint.svg" height="18" align="center"/> [`prefer-object-spread`](https://eslint.org/docs/rules/prefer-object-spread)
347
+
348
+ ```typescript
349
+ // very bad
350
+ const original = { a: 1, b: 2 };
351
+ const copy = Object.assign(original, { c: 3 }); // this mutates `original` ಠ_ಠ
352
+ delete copy.a; // so does this
353
+
354
+ // bad
355
+ const original = { a: 1, b: 2 };
356
+ const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 }
357
+
358
+ // good
359
+ const original = { a: 1, b: 2 };
360
+ const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 }
361
+
362
+ const { a, ...noA } = copy; // noA => { b: 2, c: 3 }
363
+ ```
364
+
365
+ **[⬆ back to top](#table-of-contents)**
366
+
367
+ ## Arrays
368
+
369
+ <a name="arrays--literals"></a>
370
+ [**4.1**](#arrays--literals) ‣ Use the literal syntax for array creation, except in the case of initializing a sparse array with a specific size.
371
+
372
+ <img src="../eslint.svg" height="18" align="center"/> [`no-array-constructor`](https://eslint.org/docs/rules/no-array-constructor.html)
373
+
374
+ ```typescript
375
+ // bad
376
+ const items = new Array();
377
+
378
+ // good
379
+ const items = [];
380
+
381
+ // good
382
+ const items = new Array(8);
383
+ ```
384
+
385
+ ---
386
+
387
+ <a name="arrays--push"></a>
388
+ [**4.2**](#arrays--push) ‣ Use [Array#push](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push) instead of direct assignment to add items to an array.
389
+
390
+ ```typescript
391
+ const someStack = [];
392
+
393
+ // bad
394
+ someStack[someStack.length] = 'abracadabra';
395
+
396
+ // good
397
+ someStack.push('abracadabra');
398
+ ```
399
+
400
+ ---
401
+
402
+ <a name="es6-array-spreads"></a>
403
+ [**4.3**](#es6-array-spreads) ‣ Use array spreads `...` to copy arrays.
404
+
405
+ ```typescript
406
+ // bad
407
+ const len = items.length;
408
+ const itemsCopy = [];
409
+ let i;
410
+
411
+ for (i = 0; i < len; i += 1) {
412
+ itemsCopy[i] = items[i];
413
+ }
414
+
415
+ // good
416
+ const itemsCopy = [...items];
417
+ ```
418
+
419
+ ---
420
+
421
+ <a name="arrays--from-iterable"></a>
422
+ [**4.4**](#arrays--from-iterable) ‣ To convert an iterable object to an array, use spreads `...` instead of [`Array.from`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from).
423
+
424
+ ```typescript
425
+ const foo = document.querySelectorAll('.foo');
426
+
427
+ // good
428
+ const nodes = Array.from(foo);
429
+
430
+ // best
431
+ const nodes = [...foo];
432
+ ```
433
+
434
+ ---
435
+
436
+ <a name="arrays--from-array-like"></a>
437
+ [**4.5**](#arrays--from-array-like) ‣ Use [`Array.from`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from) for converting an array-like object to an array.
438
+
439
+ ```typescript
440
+ const arrLike = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 };
441
+
442
+ // bad
443
+ const arr = Array.prototype.slice.call(arrLike);
444
+
445
+ // good
446
+ const arr = Array.from(arrLike);
447
+ ```
448
+
449
+ ---
450
+
451
+ <a name="arrays--mapping"></a>
452
+ [**4.6**](#arrays--mapping) ‣ Use [`Array.from`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from) instead of spread `...` for mapping over iterables, because it avoids creating an intermediate array.
453
+
454
+ ```typescript
455
+ // bad
456
+ const baz = [...foo].map(bar);
457
+
458
+ // good
459
+ const baz = Array.from(foo, bar);
460
+ ```
461
+
462
+ ---
463
+
464
+ <a name="arrays--callback-return"></a>
465
+ [**4.7**](#arrays--callback-return) ‣ Use return statements in array method callbacks. It’s ok to omit the return if the function body consists of a single statement returning an expression without side effects, following [**9.2**](#arrows--implicit-return).
466
+
467
+ <img src="../eslint.svg" height="18" align="center"/> [`array-callback-return`](https://eslint.org/docs/rules/array-callback-return)
468
+
469
+ ```typescript
470
+ // good
471
+ [1, 2, 3].map((x) => {
472
+ const y = x + 1;
473
+ return x * y;
474
+ });
475
+
476
+ // good
477
+ [1, 2, 3].map((x) => x + 1);
478
+
479
+ // bad - no returned value means `acc` becomes undefined after the first iteration
480
+ [[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => {
481
+ const flatten = acc.concat(item);
482
+ });
483
+
484
+ // good
485
+ [[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => {
486
+ const flatten = acc.concat(item);
487
+ return flatten;
488
+ });
489
+
490
+ // bad
491
+ inbox.filter((msg) => {
492
+ const { subject, author } = msg;
493
+ if (subject === 'Mockingbird') {
494
+ return author === 'Harper Lee';
495
+ }
496
+ });
497
+
498
+ // good
499
+ inbox.filter((msg) => {
500
+ const { subject, author } = msg;
501
+ if (subject === 'Mockingbird') {
502
+ return author === 'Harper Lee';
503
+ }
504
+
505
+ return false;
506
+ });
507
+ ```
508
+
509
+ ---
510
+
511
+ <a name="arrays--bracket-newline"></a>
512
+ [**4.8**](#arrays--bracket-newline) ‣ Use line breaks after open and before close array brackets if an array has multiple lines.
513
+
514
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
515
+
516
+ ```typescript
517
+ // bad
518
+ const arr = [
519
+ [0, 1],
520
+ ];
521
+
522
+ const objectInArray = [{
523
+ id: 1,
524
+ }, {
525
+ id: 2,
526
+ }];
527
+
528
+ const numberInArray = [
529
+ 1, 2,
530
+ ];
531
+
532
+ // good
533
+ const arr = [[0, 1]];
534
+
535
+ const objectInArray = [
536
+ {
537
+ id: 1,
538
+ },
539
+ {
540
+ id: 2,
541
+ },
542
+ ];
543
+
544
+ const stringInArray = [
545
+ 'foofoofoofoofoofoofoofoo',
546
+ 'foofoofoofoofoofoofoofoo',
547
+ 'foofoofoofoofoofoofoofoo',
548
+ ];
549
+ ```
550
+
551
+ ---
552
+
553
+ <a name="arrays--sort-compare"></a>
554
+ [**4.9**](#arrays--sort-compare) ‣ Always provide a comparison function to `Array#sort`.
555
+
556
+ <img src="../eslint.svg" height="18" align="center"/> [`@typescript-eslint/require-array-sort-compare`](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/require-array-sort-compare.md)
557
+
558
+ > Why? `Array#sort` is one of those old-school Javascript things that does not behave the way you would expect. If you don't pass in your own comparison function, it converts all the contents to strings and sorts alphabetically.
559
+
560
+ ```typescript
561
+ // bad
562
+ const thanksBrendan = [30, 10, 3, 2, 20, 1].sort();
563
+ // -> [1, 10, 2, 20, 3, 30]
564
+
565
+ // good
566
+ const ahThatsBetter = [30, 10, 3, 2, 20, 1].sort((a, b) => a - b);
567
+ // -> [1, 2, 3, 10, 20, 30]
568
+ ```
569
+
570
+ **[⬆ back to top](#table-of-contents)**
571
+
572
+ ## Destructuring
573
+
574
+ <a name="destructuring--object"></a>
575
+ [**5.1**](#destructuring--object) ‣ Use object destructuring when accessing and using multiple properties of an object.
576
+
577
+ <img src="../eslint.svg" height="18" align="center"/> [`prefer-destructuring`](https://eslint.org/docs/rules/prefer-destructuring)
578
+
579
+ > Why? Destructuring saves you from creating temporary references for those properties, and from repetitive access of the object. Repeating object access creates more repetitive code, requires more reading, and creates more opportunities for mistakes. Destructuring objects also provides a single site of definition of the object structure that is used in the block, rather than requiring reading the entire block to determine what is used.
580
+
581
+ ```typescript
582
+ // bad
583
+ function getFullName(user) {
584
+ const firstName = user.firstName;
585
+ const lastName = user.lastName;
586
+
587
+ return `${firstName} ${lastName}`;
588
+ }
589
+
590
+ // good
591
+ function getFullName(user) {
592
+ const { firstName, lastName } = user;
593
+ return `${firstName} ${lastName}`;
594
+ }
595
+
596
+ // best
597
+ function getFullName({ firstName, lastName }) {
598
+ return `${firstName} ${lastName}`;
599
+ }
600
+ ```
601
+
602
+ ---
603
+
604
+ <a name="destructuring--array"></a>
605
+ [**5.2**](#destructuring--array) ‣ Use array destructuring.
606
+
607
+ <img src="../eslint.svg" height="18" align="center"/> [`prefer-destructuring`](https://eslint.org/docs/rules/prefer-destructuring)
608
+
609
+ ```typescript
610
+ const arr = [1, 2, 3, 4];
611
+
612
+ // bad
613
+ const first = arr[0];
614
+ const second = arr[1];
615
+
616
+ // good
617
+ const [first, second] = arr;
618
+ ```
619
+
620
+ ---
621
+
622
+ <a name="destructuring--object-over-array"></a>
623
+ [**5.3**](#destructuring--object-over-array) ‣ Use object destructuring for multiple return values, not array destructuring.
624
+
625
+ > Why? You can add new properties over time or change the order of things without breaking call sites.
626
+
627
+ ```typescript
628
+ // bad
629
+ function processInput(input) {
630
+ // then a miracle occurs
631
+ return [left, right, top, bottom];
632
+ }
633
+
634
+ // the caller needs to think about the order of return data
635
+ const [left, __, top] = processInput(input);
636
+
637
+ // good
638
+ function processInput(input) {
639
+ // then a miracle occurs
640
+ return { left, right, top, bottom };
641
+ }
642
+
643
+ // the caller selects only the data they need
644
+ const { left, top } = processInput(input);
645
+ ```
646
+
647
+ **[⬆ back to top](#table-of-contents)**
648
+
649
+ ## Strings
650
+
651
+ <a name="strings--quotes"></a>
652
+ [**6.1**](#strings--quotes) ‣ Use double quotes `""` for strings.
653
+
654
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
655
+
656
+ <img src="../eslint.svg" height="18" align="center"/> [`quotes`](https://eslint.org/docs/rules/quotes.html)
657
+
658
+ > Why? In a JSX world, double quotes result in your code needing fewer escapes than single quotes.
659
+
660
+ ```typescript
661
+ // bad
662
+ const name = 'Let\'s all go to the movies';
663
+
664
+ // bad - template literals should contain interpolation or newlines
665
+ const name = `Let's all go to the movies`;
666
+
667
+ // good
668
+ const name = "Let's all go to the movies";
669
+ ```
670
+
671
+ ---
672
+
673
+ <a name="strings--line-length"></a>
674
+ [**6.2**](#strings--line-length) ‣ Strings that cause the line to go over 100 characters should not be written across multiple lines using string concatenation.
675
+
676
+ > Why? Broken strings are painful to work with and make code less searchable.
677
+
678
+ ```typescript
679
+ // bad
680
+ const errorMessage = 'This is a super long error that was thrown because \
681
+ of Batman. When you stop to think about how Batman had anything to do \
682
+ with this, you would get nowhere \
683
+ fast.';
684
+
685
+ // bad
686
+ const errorMessage = 'This is a super long error that was thrown because ' +
687
+ 'of Batman. When you stop to think about how Batman had anything to do ' +
688
+ 'with this, you would get nowhere fast.';
689
+
690
+ // good
691
+ const errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';
692
+ ```
693
+
694
+ ---
695
+
696
+ <a name="es6-template-literals"></a>
697
+ [**6.3**](#es6-template-literals) ‣ When programmatically building up strings, use template strings instead of concatenation.
698
+
699
+ <img src="../eslint.svg" height="18" align="center"/> [`prefer-template`](https://eslint.org/docs/rules/prefer-template.html), [`template-curly-spacing`](https://eslint.org/docs/rules/template-curly-spacing)
700
+
701
+ > Why? Template strings give you a readable, concise syntax with proper newlines and string interpolation features.
702
+
703
+ ```typescript
704
+ // bad
705
+ function sayHi(name) {
706
+ return 'How are you, ' + name + '?';
707
+ }
708
+
709
+ // bad
710
+ function sayHi(name) {
711
+ return ['How are you, ', name, '?'].join();
712
+ }
713
+
714
+ // bad
715
+ function sayHi(name) {
716
+ return `How are you, ${ name }?`;
717
+ }
718
+
719
+ // good
720
+ function sayHi(name) {
721
+ return `How are you, ${name}?`;
722
+ }
723
+ ```
724
+
725
+ ---
726
+
727
+ <a name="strings--eval"></a>
728
+ [**6.4**](#strings--eval) ‣ Never use `eval()` on a string, it opens too many vulnerabilities.
729
+
730
+ <img src="../eslint.svg" height="18" align="center"/> [`no-eval`](https://eslint.org/docs/rules/no-eval)
731
+
732
+ ---
733
+
734
+ <a name="strings--escaping"></a>
735
+ [**6.5**](#strings--escaping) ‣ Do not unnecessarily escape characters in strings.
736
+
737
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
738
+
739
+ <img src="../eslint.svg" height="18" align="center"/> [`no-useless-escape`](https://eslint.org/docs/rules/no-useless-escape)
740
+
741
+ > Why? Backslashes harm readability, thus they should only be present when necessary.
742
+
743
+ ```typescript
744
+ // bad
745
+ const foo = '\'this\' \i\s \"quoted\"';
746
+
747
+ // good
748
+ const foo = '\'this\' is "quoted"';
749
+ const foo = `my name is '${name}'`;
750
+ ```
751
+
752
+ **[⬆ back to top](#table-of-contents)**
753
+
754
+ ## Promises
755
+
756
+ <a name="promises--handle-errors"></a>
757
+ [**7.1**](#promises--handle-errors) ‣ When awaiting a promise, the potential for it to be rejected must be handled.
758
+
759
+ <img src="../eslint.svg" height="18" align="center"/> [`@typescript-eslint/no-floating-promises`](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-floating-promises.md)
760
+
761
+ > Why? We've all seen "Unhandled Promise rejection" before and not once has that error ever been useful in debugging the issue. Do yourself a favor and catch Promise errors so you can at least log out a useful error object.
762
+
763
+ ```typescript
764
+ // bad
765
+ someBackendCall().then((result) => {
766
+ // ...
767
+ });
768
+
769
+ // good
770
+ someBackendCall()
771
+ .then((result) => {
772
+ // ...
773
+ })
774
+ .catch((err) => {
775
+ console.error(err);
776
+ // other error handling maybe
777
+ });
778
+
779
+ // bad
780
+ const result = await someBackendCall();
781
+
782
+ // good
783
+ try {
784
+ const result = await someBackendCall();
785
+ } catch (err) {
786
+ console.error(err);
787
+ // other error handling maybe
788
+ }
789
+ ```
790
+
791
+ <a name="promises--void"></a>
792
+ [**7.2**](#promises--void) ‣ You can have a "fire-and-forget" Promise that is not awaited if you explicitly mark it as such with the `void` operator.
793
+
794
+ ```typescript
795
+ // bad, will produce an eslint error for the above rule about handling errors
796
+ someBackendCall(); // (returns a Promise)
797
+
798
+ // good, now it is explicit that we mean to just fire this off and move on
799
+ void someBackendCall();
800
+ ```
801
+
802
+ **[⬆ back to top](#table-of-contents)**
803
+
804
+ ## Functions
805
+
806
+ <a name="functions--in-blocks"></a>
807
+ [**8.1**](#functions--in-blocks) ‣ Never declare a function in a non-function block (`if`, `while`, etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news bears.
808
+
809
+ <img src="../eslint.svg" height="18" align="center"/> [`no-loop-func`](https://eslint.org/docs/rules/no-loop-func.html)
810
+
811
+ ---
812
+
813
+ <a name="functions--note-on-blocks"></a>
814
+ 💡 [**8.2**](#functions--note-on-blocks) ‣ **Note:** ECMA-262 defines a `block` as a list of statements. A function declaration is not a statement.
815
+
816
+ ```typescript
817
+ // bad
818
+ if (currentUser) {
819
+ function test() {
820
+ console.log('Nope.');
821
+ }
822
+ }
823
+
824
+ // good
825
+ let test;
826
+ if (currentUser) {
827
+ test = () => {
828
+ console.log('Yup.');
829
+ };
830
+ }
831
+ ```
832
+
833
+ ---
834
+
835
+ <a name="es6-rest"></a>
836
+ [**8.3**](#es6-rest) ‣ Never use `arguments`, opt to use rest syntax `...` instead.
837
+
838
+ <img src="../eslint.svg" height="18" align="center"/> [`prefer-rest-params`](https://eslint.org/docs/rules/prefer-rest-params)
839
+
840
+ > Why? `...` is explicit about which arguments you want pulled. Plus, rest arguments are a real Array, and not merely Array-like like `arguments`.
841
+
842
+ ```typescript
843
+ // bad
844
+ function concatenateAll() {
845
+ const args = Array.prototype.slice.call(arguments);
846
+ return args.join('');
847
+ }
848
+
849
+ // good
850
+ function concatenateAll(...args) {
851
+ return args.join('');
852
+ }
853
+ ```
854
+
855
+ ---
856
+
857
+ <a name="es6-default-parameters"></a>
858
+ [**8.4**](#es6-default-parameters) ‣ Use default parameter syntax rather than mutating function arguments.
859
+
860
+ ```typescript
861
+ // really bad
862
+ function handleThings(opts) {
863
+ // No! We shouldn’t mutate function arguments.
864
+ // Double bad: if opts is falsy it'll be set to an object which may
865
+ // be what you want but it can introduce subtle bugs.
866
+ opts = opts || {};
867
+ // ...
868
+ }
869
+
870
+ // still bad
871
+ function handleThings(opts) {
872
+ if (opts === void 0) {
873
+ opts = {};
874
+ }
875
+ // ...
876
+ }
877
+
878
+ // good
879
+ function handleThings(opts = {}) {
880
+ // ...
881
+ }
882
+ ```
883
+
884
+ ---
885
+
886
+ <a name="functions--default-side-effects"></a>
887
+ [**8.5**](#functions--default-side-effects) ‣ Avoid side effects with default parameters.
888
+
889
+ > Why? They are confusing to reason about.
890
+
891
+
892
+ ```typescript
893
+ let b = 1;
894
+
895
+ // bad
896
+ function count(a = b++) {
897
+ console.log(a);
898
+ }
899
+ count(); // 1
900
+ count(); // 2
901
+ count(3); // 3
902
+ count(); // 3
903
+ ```
904
+
905
+ ---
906
+
907
+ <a name="functions--defaults-last"></a>
908
+ [**8.6**](#functions--defaults-last) ‣ Always put default parameters last.
909
+
910
+ <img src="../eslint.svg" height="18" align="center"/> [`default-param-last`](https://eslint.org/docs/rules/default-param-last)
911
+
912
+ ```typescript
913
+ // bad
914
+ function handleThings(opts: IHandleThingsOpts = {}, name: string) {
915
+ // ...
916
+ }
917
+
918
+ // good
919
+ function handleThings(name: string, opts: IHandleThingsOpts = {}) {
920
+ // ...
921
+ }
922
+ ```
923
+
924
+ ---
925
+
926
+ <a name="functions--constructor"></a>
927
+ [**8.7**](#functions--constructor) ‣ Never use the Function constructor to create a new function.
928
+
929
+ <img src="../eslint.svg" height="18" align="center"/> [`no-new-func`](https://eslint.org/docs/rules/no-new-func)
930
+
931
+ > Why? Creating a function in this way evaluates a string similarly to `eval()`, which opens vulnerabilities.
932
+
933
+ ```typescript
934
+ // bad
935
+ const add = new Function('a', 'b', 'return a + b');
936
+
937
+ // still bad
938
+ const subtract = Function('a', 'b', 'return a - b');
939
+ ```
940
+
941
+ ---
942
+
943
+ <a name="functions--signature-spacing"></a>
944
+ [**8.8**](#functions--signature-spacing) ‣ Spacing in a function signature.
945
+
946
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
947
+
948
+ <img src="../eslint.svg" height="18" align="center"/> [`space-before-function-paren`](https://eslint.org/docs/rules/space-before-function-paren), [`space-before-blocks`](https://eslint.org/docs/rules/space-before-blocks)
949
+
950
+ > Why? Consistency is good, and you shouldn’t have to add or remove a space when adding or removing a name.
951
+
952
+ ```typescript
953
+ // bad
954
+ const f = function(){};
955
+ const g = function (){};
956
+ const h = function() {};
957
+
958
+ // good
959
+ const x = function () {};
960
+ const y = function a() {};
961
+ ```
962
+
963
+ ---
964
+
965
+ <a name="functions--mutate-params"></a>
966
+ [**8.10**](#functions--mutate-params) ‣ Never mutate parameters.
967
+
968
+ <img src="../eslint.svg" height="18" align="center"/> [`no-param-reassign`](https://eslint.org/docs/rules/no-param-reassign.html)
969
+
970
+ > Why? Manipulating objects passed in as parameters can cause unwanted variable side effects in the original caller.
971
+
972
+ ```typescript
973
+ // bad
974
+ function f1(obj: ObjType) {
975
+ obj.key = 1;
976
+ // ...
977
+ }
978
+
979
+ // good
980
+ function f2(obj: ObjType) {
981
+ const objCopy = {
982
+ ...obj,
983
+ key: 1,
984
+ };
985
+ // ...
986
+ }
987
+ ```
988
+
989
+ ---
990
+
991
+ <a name="functions--reassign-params"></a>
992
+ [**8.11**](#functions--reassign-params) ‣ Never reassign parameters.
993
+
994
+ <img src="../eslint.svg" height="18" align="center"/> [`no-param-reassign`](https://eslint.org/docs/rules/no-param-reassign.html)
995
+
996
+ > Why? Reassigning parameters can lead to unexpected behavior, especially when accessing the `arguments` object. It can also cause optimization issues, especially in V8.
997
+
998
+ ```typescript
999
+ // bad
1000
+ function f1(a: number) {
1001
+ a = 1;
1002
+ // ...
1003
+ }
1004
+
1005
+ function f2(a: number) {
1006
+ if (!a) { a = 1; }
1007
+ // ...
1008
+ }
1009
+
1010
+ // good
1011
+ function f3(a: number) {
1012
+ const b = a || 1;
1013
+ // ...
1014
+ }
1015
+
1016
+ function f4(a: number = 1) {
1017
+ // ...
1018
+ }
1019
+ ```
1020
+
1021
+ ---
1022
+
1023
+ <a name="functions--spread-vs-apply"></a>
1024
+ [**8.12**](#functions--spread-vs-apply) ‣ Prefer the use of the spread syntax `...` to call variadic functions.
1025
+
1026
+ <img src="../eslint.svg" height="18" align="center"/> [`prefer-spread`](https://eslint.org/docs/rules/prefer-spread)
1027
+
1028
+ > Why? It’s cleaner, you don’t need to supply a context, and you can not easily compose `new` with `apply`.
1029
+
1030
+ ```typescript
1031
+ // bad
1032
+ const x = [1, 2, 3, 4, 5];
1033
+ console.log.apply(console, x);
1034
+
1035
+ // good
1036
+ const x = [1, 2, 3, 4, 5];
1037
+ console.log(...x);
1038
+
1039
+ // bad
1040
+ new (Function.prototype.bind.apply(Date, [null, 2016, 8, 5]));
1041
+
1042
+ // good
1043
+ new Date(...[2016, 8, 5]);
1044
+ ```
1045
+
1046
+ ---
1047
+
1048
+ <a name="functions--signature-invocation-indentation"></a>
1049
+ [**8.13**](#functions--signature-invocation-indentation) ‣ Functions with multiline signatures, or invocations, should be indented just like every other multiline list in this guide: with each item on a line by itself, with a trailing comma on the last item.
1050
+
1051
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
1052
+
1053
+ ```typescript
1054
+ // bad
1055
+ function foo(bar: string,
1056
+ baz: number,
1057
+ quux: boolean) {
1058
+ // ...
1059
+ }
1060
+
1061
+ // good
1062
+ function foo(
1063
+ bar: string,
1064
+ baz: number,
1065
+ quux: boolean,
1066
+ ) {
1067
+ // ...
1068
+ }
1069
+
1070
+ // bad
1071
+ console.log(foo,
1072
+ bar,
1073
+ baz);
1074
+
1075
+ // good
1076
+ console.log(
1077
+ foo,
1078
+ bar,
1079
+ baz,
1080
+ );
1081
+ ```
1082
+
1083
+ ---
1084
+
1085
+ <a name="functions--return-type"></a>
1086
+ [**8.14**](#functions--return-type) ‣ Functions and methods should include an explicit return type.
1087
+
1088
+ <img src="../eslint.svg" height="18" align="center"/> [`@typescript-eslint/explicit-function-return-type`](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/explicit-function-return-type.md)
1089
+
1090
+ > Why? If you explicitly specify what the function is intended to return, then a bug where it returns something unintended will be caught immediately in your IDE. If you allow TypeScript to infer the return type, it will assume anything the function ends up returning is fine. (We acknowledge the examples throughout this document often don't follow this. Time permitting we will possibly correct that.)
1091
+
1092
+ ```typescript
1093
+ // bad
1094
+ function foo(isTwo: boolean) {
1095
+ if (isTwo) {
1096
+ return 2;
1097
+ }
1098
+ }
1099
+
1100
+ /** good - this will show a TS error because the
1101
+ * code as written could return `undefined`, prompting
1102
+ * you to think about what you want: should it actually
1103
+ * always return a number, or should it be the way it is?
1104
+ * If so, then you can explicitly change the return type
1105
+ * to `number | undefined`. */
1106
+ function foo(isTwo: boolean): number {
1107
+ if (isTwo) {
1108
+ return 2;
1109
+ }
1110
+ }
1111
+ ```
1112
+
1113
+ **[⬆ back to top](#table-of-contents)**
1114
+
1115
+ ## Arrow Functions
1116
+
1117
+ <a name="arrows--use-them"></a>
1118
+ [**9.1**](#arrows--use-them) ‣ When you must use an anonymous function (as when passing an inline callback), use arrow function notation.
1119
+
1120
+ <img src="../eslint.svg" height="18" align="center"/> [`prefer-arrow-callback`](https://eslint.org/docs/rules/prefer-arrow-callback.html), [`arrow-spacing`](https://eslint.org/docs/rules/arrow-spacing.html)
1121
+
1122
+ > Why? It creates a version of the function that executes in the context of `this`, which is usually what you want, and is a more concise syntax.
1123
+
1124
+ > Why not? If you have a fairly complicated function, you might move that logic out into its own named function expression.
1125
+
1126
+ ```typescript
1127
+ // bad
1128
+ [1, 2, 3].map(function (x) {
1129
+ const y = x + 1;
1130
+ return x * y;
1131
+ });
1132
+
1133
+ // good
1134
+ [1, 2, 3].map((x) => {
1135
+ const y = x + 1;
1136
+ return x * y;
1137
+ });
1138
+ ```
1139
+
1140
+ ---
1141
+
1142
+ <a name="arrows--implicit-return"></a>
1143
+ [**9.2**](#arrows--implicit-return) ‣ If the function body consists of a single statement returning an [expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Expressions) without side effects, omit the braces and use the implicit return. Otherwise, keep the braces and use a `return` statement.
1144
+
1145
+ <img src="../eslint.svg" height="18" align="center"/> [`arrow-parens`](https://eslint.org/docs/rules/arrow-parens.html), [`arrow-body-style`](https://eslint.org/docs/rules/arrow-body-style.html)
1146
+
1147
+ > Why? Syntactic sugar. It reads well when multiple functions are chained together.
1148
+
1149
+ ```typescript
1150
+ // bad
1151
+ [1, 2, 3].map((number) => {
1152
+ const nextNumber = number + 1;
1153
+ `A string containing the ${nextNumber}.`;
1154
+ });
1155
+
1156
+ // good
1157
+ [1, 2, 3].map((number) => `A string containing the ${number + 1}.`);
1158
+
1159
+ // good
1160
+ [1, 2, 3].map((number) => {
1161
+ const nextNumber = number + 1;
1162
+ return `A string containing the ${nextNumber}.`;
1163
+ });
1164
+
1165
+ // good
1166
+ [1, 2, 3].map((number, index) => ({
1167
+ [index]: number,
1168
+ }));
1169
+
1170
+ // No implicit return with side effects
1171
+ function foo(callback: () => boolean) {
1172
+ const val = callback();
1173
+ if (val === true) {
1174
+ // Do something if callback returns true
1175
+ }
1176
+ }
1177
+
1178
+ let bool = false;
1179
+
1180
+ // bad
1181
+ foo(() => bool = true);
1182
+
1183
+ // good
1184
+ foo(() => {
1185
+ bool = true;
1186
+ });
1187
+ ```
1188
+
1189
+ ---
1190
+
1191
+ <a name="arrows--paren-wrap"></a>
1192
+ [**9.3**](#arrows--paren-wrap) ‣ In case the expression spans over multiple lines, wrap it in parentheses for better readability.
1193
+
1194
+ > Why? It shows clearly where the function starts and ends.
1195
+
1196
+ ```typescript
1197
+ // bad
1198
+ ['get', 'post', 'put'].map((httpMethod) => Object.prototype.hasOwnProperty.call(
1199
+ httpMagicObjectWithAVeryLongName,
1200
+ httpMethod,
1201
+ )
1202
+ );
1203
+
1204
+ // good
1205
+ ['get', 'post', 'put'].map((httpMethod) => (
1206
+ Object.prototype.hasOwnProperty.call(
1207
+ httpMagicObjectWithAVeryLongName,
1208
+ httpMethod,
1209
+ )
1210
+ ));
1211
+ ```
1212
+
1213
+ ---
1214
+
1215
+ <a name="arrows--one-arg-parens"></a>
1216
+ [**9.4**](#arrows--one-arg-parens) ‣ Always include parentheses around arguments for clarity and consistency.
1217
+
1218
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
1219
+
1220
+ <img src="../eslint.svg" height="18" align="center"/> [`arrow-parens`](https://eslint.org/docs/rules/arrow-parens.html)
1221
+
1222
+ > Why? Minimizes diff churn when adding or removing arguments.
1223
+
1224
+ ```typescript
1225
+ // bad
1226
+ [1, 2, 3].map(x => x * x);
1227
+
1228
+ // good
1229
+ [1, 2, 3].map((x) => x * x);
1230
+
1231
+ // bad
1232
+ [1, 2, 3].map(number => (
1233
+ `A long string with the ${number}. It’s so long that we don’t want it to take up space on the .map line!`
1234
+ ));
1235
+
1236
+ // good
1237
+ [1, 2, 3].map((number) => (
1238
+ `A long string with the ${number}. It’s so long that we don’t want it to take up space on the .map line!`
1239
+ ));
1240
+
1241
+ // bad
1242
+ [1, 2, 3].map(x => {
1243
+ const y = x + 1;
1244
+ return x * y;
1245
+ });
1246
+
1247
+ // good
1248
+ [1, 2, 3].map((x) => {
1249
+ const y = x + 1;
1250
+ return x * y;
1251
+ });
1252
+ ```
1253
+
1254
+ ---
1255
+
1256
+ <a name="arrows--confusing"></a>
1257
+ [**9.5**](#arrows--confusing) ‣ Avoid confusing arrow function syntax (`=>`) with comparison operators (`<=`, `>=`).
1258
+
1259
+ <img src="../eslint.svg" height="18" align="center"/> [`no-confusing-arrow`](https://eslint.org/docs/rules/no-confusing-arrow)
1260
+
1261
+ ```typescript
1262
+ // bad
1263
+ const itemHeight = (item: ItemType) => item.height <= 256 ? item.largeSize : item.smallSize;
1264
+
1265
+ // bad
1266
+ const itemHeight = (item: ItemType) => item.height >= 256 ? item.largeSize : item.smallSize;
1267
+
1268
+ // good
1269
+ const itemHeight = (item: ItemType) => (item.height <= 256 ? item.largeSize : item.smallSize);
1270
+
1271
+ // good
1272
+ const itemHeight = (item: ItemType) => {
1273
+ const { height, largeSize, smallSize } = item;
1274
+ return height <= 256 ? largeSize : smallSize;
1275
+ };
1276
+ ```
1277
+
1278
+ ---
1279
+
1280
+ <a name="arrows--implicit-arrow-linebreak"></a>
1281
+ [**9.6**](#arrows--implicit-arrow-linebreak) ‣ Enforce the location of arrow function bodies with implicit returns.
1282
+
1283
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
1284
+
1285
+ ```typescript
1286
+ // bad
1287
+ (foo) =>
1288
+ bar;
1289
+
1290
+ (foo) =>
1291
+ (bar);
1292
+
1293
+ // good
1294
+ (foo) => bar;
1295
+ (foo) => (bar);
1296
+ (foo) => (
1297
+ bar
1298
+ )
1299
+ ```
1300
+
1301
+ **[⬆ back to top](#table-of-contents)**
1302
+
1303
+ ## Classes & Constructors
1304
+
1305
+ <a name="constructors--use-class"></a>
1306
+ [**10.1**](#constructors--use-class) ‣ Always use `class`. Avoid manipulating `prototype` directly.
1307
+
1308
+ > Why? `class` syntax is more concise and easier to reason about.
1309
+
1310
+ ```typescript
1311
+ // bad
1312
+ function Queue(contents = []) {
1313
+ this.queue = [...contents];
1314
+ }
1315
+ Queue.prototype.pop = function () {
1316
+ const value = this.queue[0];
1317
+ this.queue.splice(0, 1);
1318
+ return value;
1319
+ };
1320
+
1321
+ // good
1322
+ class Queue<T> {
1323
+ queue: T[];
1324
+
1325
+ constructor(contents: T[] = []) {
1326
+ this.queue = [...contents];
1327
+ }
1328
+
1329
+ pop(): T {
1330
+ const value = this.queue[0];
1331
+ this.queue.splice(0, 1);
1332
+ return value;
1333
+ }
1334
+ }
1335
+ ```
1336
+
1337
+ ---
1338
+
1339
+ <a name="constructors--extends"></a>
1340
+ [**10.2**](#constructors--extends) ‣ Use `extends` for inheritance.
1341
+
1342
+ > Why? It is a built-in way to inherit prototype functionality without breaking `instanceof`.
1343
+
1344
+ ```typescript
1345
+ // bad
1346
+ const inherits = require('inherits');
1347
+ function PeekableQueue(contents) {
1348
+ Queue.apply(this, contents);
1349
+ }
1350
+ inherits(PeekableQueue, Queue);
1351
+ PeekableQueue.prototype.peek = function () {
1352
+ return this.queue[0];
1353
+ };
1354
+
1355
+ // good
1356
+ class PeekableQueue<T> extends Queue<T> {
1357
+ peek(): T {
1358
+ return this.queue[0];
1359
+ }
1360
+ }
1361
+ ```
1362
+
1363
+ ---
1364
+
1365
+ <a name="constructors--chaining"></a>
1366
+ 💡 [**10.3**](#constructors--chaining) ‣ Methods can return `this` to help with method chaining.
1367
+
1368
+ ```typescript
1369
+ // bad
1370
+ Jedi.prototype.jump = function () {
1371
+ this.jumping = true;
1372
+ return true;
1373
+ };
1374
+
1375
+ Jedi.prototype.setHeight = function (height) {
1376
+ this.height = height;
1377
+ };
1378
+
1379
+ const luke = new Jedi();
1380
+ luke.jump(); // => true
1381
+ luke.setHeight(20); // => undefined
1382
+
1383
+ // good
1384
+ class Jedi {
1385
+ jumping = false;
1386
+ height: number;
1387
+
1388
+ jump(): this {
1389
+ this.jumping = true;
1390
+ return this;
1391
+ }
1392
+
1393
+ setHeight(height: number): this {
1394
+ this.height = height;
1395
+ return this;
1396
+ }
1397
+ }
1398
+
1399
+ const luke = new Jedi();
1400
+
1401
+ luke.jump()
1402
+ .setHeight(20);
1403
+ ```
1404
+
1405
+ ---
1406
+
1407
+ <a name="constructors--tostring"></a>
1408
+ [**10.4**](#constructors--tostring) ‣ It’s okay to write a custom `toString()` method, just make sure it works successfully and causes no side effects.
1409
+
1410
+ ```typescript
1411
+ class Jedi {
1412
+ name: string;
1413
+
1414
+ constructor(options: IJediOptions = {}) {
1415
+ this.name = options.name || 'no name';
1416
+ }
1417
+
1418
+ getName(): string {
1419
+ return this.name;
1420
+ }
1421
+
1422
+ toString(): string {
1423
+ return `Jedi - ${this.getName()}`;
1424
+ }
1425
+ }
1426
+ ```
1427
+
1428
+ ---
1429
+
1430
+ <a name="constructors--no-useless"></a>
1431
+ [**10.5**](#constructors--no-useless) ‣ Classes have a default constructor if one is not specified. An empty constructor function or one that just delegates to a parent class is unnecessary.
1432
+
1433
+ <img src="../eslint.svg" height="18" align="center"/> [`no-useless-constructor`](https://eslint.org/docs/rules/no-useless-constructor)
1434
+
1435
+ ```typescript
1436
+ // bad
1437
+ class Jedi {
1438
+ name: string;
1439
+
1440
+ constructor() {}
1441
+
1442
+ getName() {
1443
+ return this.name;
1444
+ }
1445
+ }
1446
+
1447
+ // bad
1448
+ class Rey extends Jedi {
1449
+ constructor(...args) {
1450
+ super(...args);
1451
+ }
1452
+ }
1453
+
1454
+ // good
1455
+ class Rey extends Jedi {
1456
+ constructor(...args) {
1457
+ super(...args);
1458
+ this.name = 'Rey';
1459
+ }
1460
+ }
1461
+ ```
1462
+
1463
+ ---
1464
+
1465
+ <a name="classes--no-duplicate-members"></a>
1466
+ [**10.6**](#classes--no-duplicate-members) ‣ Avoid duplicate class members.
1467
+
1468
+ <img src="../eslint.svg" height="18" align="center"/> [`no-dupe-class-members`](https://eslint.org/docs/rules/no-dupe-class-members)
1469
+
1470
+ > Why? Duplicate class member declarations will silently prefer the last one - having duplicates is almost certainly a bug.
1471
+
1472
+ ```typescript
1473
+ // bad
1474
+ class Foo {
1475
+ bar() { return 1; }
1476
+ bar() { return 2; }
1477
+ }
1478
+
1479
+ // good
1480
+ class Foo {
1481
+ bar() { return 1; }
1482
+ }
1483
+
1484
+ // good
1485
+ class Foo {
1486
+ bar() { return 2; }
1487
+ }
1488
+ ```
1489
+
1490
+ ---
1491
+
1492
+ <a name="classes--methods-use-this"></a>
1493
+ [**10.7**](#classes--methods-use-this) ‣ Class methods should use `this` or be made into a static method unless an external library or framework requires using specific non-static methods. Being an instance method should indicate that it behaves differently based on properties of the receiver.
1494
+
1495
+ <img src="../eslint.svg" height="18" align="center"/> [`class-methods-use-this`](https://eslint.org/docs/rules/class-methods-use-this)
1496
+
1497
+ ```typescript
1498
+ // bad
1499
+ class Foo {
1500
+ bar() {
1501
+ console.log('bar');
1502
+ }
1503
+ }
1504
+
1505
+ // good - `this` is used
1506
+ class Foo {
1507
+ bar() {
1508
+ console.log(this.bar);
1509
+ }
1510
+ }
1511
+
1512
+ // good - constructor is exempt
1513
+ class Foo {
1514
+ constructor() {
1515
+ // ...
1516
+ }
1517
+ }
1518
+
1519
+ // good - static methods aren't expected to use this
1520
+ class Foo {
1521
+ static bar() {
1522
+ console.log('bar');
1523
+ }
1524
+ }
1525
+ ```
1526
+
1527
+ **[⬆ back to top](#table-of-contents)**
1528
+
1529
+ ## Modules
1530
+
1531
+ <a name="modules--use-them"></a>
1532
+ [**11.1**](#modules--use-them) ‣ Always use modules (`import`/`export`) over a non-standard module system. You can always transpile to your preferred module system.
1533
+
1534
+ > Why? Modules are the future, let’s start using the future now.
1535
+
1536
+ ```typescript
1537
+ // bad
1538
+ const AirbnbStyleGuide = require('./AirbnbStyleGuide');
1539
+ module.exports = AirbnbStyleGuide.es6;
1540
+
1541
+ // ok
1542
+ import AirbnbStyleGuide from './AirbnbStyleGuide';
1543
+ export default AirbnbStyleGuide.es6;
1544
+
1545
+ // best
1546
+ import { es6 } from './AirbnbStyleGuide';
1547
+ export default es6;
1548
+ ```
1549
+
1550
+ ---
1551
+
1552
+ <a name="modules--no-duplicate-imports"></a>
1553
+ [**11.2**](#modules--no-duplicate-imports) ‣ Only import from a path in one place.
1554
+
1555
+ <img src="../eslint.svg" height="18" align="center"/> [`no-duplicate-imports`](https://eslint.org/docs/rules/no-duplicate-imports)
1556
+
1557
+ > Why? Having multiple lines that import from the same path can make code harder to maintain.
1558
+
1559
+ ```typescript
1560
+ // bad
1561
+ import foo from 'foo';
1562
+ // … some other imports … //
1563
+ import { named1, named2 } from 'foo';
1564
+
1565
+ // good
1566
+ import foo, { named1, named2 } from 'foo';
1567
+
1568
+ // good
1569
+ import foo, {
1570
+ named1,
1571
+ named2,
1572
+ } from 'foo';
1573
+ ```
1574
+
1575
+ ---
1576
+
1577
+ <a name="modules--no-mutable-exports"></a>
1578
+ [**11.3**](#modules--no-mutable-exports) ‣ Do not export mutable bindings.
1579
+
1580
+ <img src="../eslint.svg" height="18" align="center"/> [`import/no-mutable-exports`](https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-mutable-exports.md)
1581
+
1582
+ > Why? Mutation should be avoided in general, but in particular when exporting mutable bindings. While this technique may be needed for some special cases, in general, only constant references should be exported.
1583
+
1584
+ ```typescript
1585
+ // bad
1586
+ let foo = 3;
1587
+ export { foo };
1588
+
1589
+ // good
1590
+ const foo = 3;
1591
+ export { foo };
1592
+ ```
1593
+
1594
+ ---
1595
+
1596
+ <a name="modules--imports-first"></a>
1597
+ [**11.4**](#modules--imports-first) ‣ Put all `import`s above non-import statements.
1598
+
1599
+ <img src="../eslint.svg" height="18" align="center"/> [`import/first`](https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/first.md)
1600
+
1601
+ > Why? Since `import`s are hoisted, keeping them all at the top prevents surprising behavior.
1602
+
1603
+ ```typescript
1604
+ // bad
1605
+ import foo from 'foo';
1606
+ foo.init();
1607
+
1608
+ import bar from 'bar';
1609
+
1610
+ // good
1611
+ import foo from 'foo';
1612
+ import bar from 'bar';
1613
+
1614
+ foo.init();
1615
+ ```
1616
+
1617
+ ---
1618
+
1619
+ <a name="modules--multiline-imports-over-newlines"></a>
1620
+ [**11.5**](#modules--multiline-imports-over-newlines) ‣ Multiline imports should be indented just like multiline array and object literals.
1621
+
1622
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
1623
+
1624
+ > Why? The curly braces follow the same indentation rules as every other curly brace block in the style guide, as do the trailing commas.
1625
+
1626
+ ```typescript
1627
+ // bad
1628
+ import { longNameA, longNameB, longNameC,
1629
+ longNameD, longNameE, longNameF } from 'path';
1630
+
1631
+ // good
1632
+ import {
1633
+ longNameA,
1634
+ longNameB,
1635
+ longNameC,
1636
+ longNameD,
1637
+ longNameE,
1638
+ } from 'path';
1639
+ ```
1640
+
1641
+ Note: formerly we used [`object-curly-newline`](https://eslint.org/docs/rules/object-curly-newline) but have turned it off due to conflicts with how Prettier handles this.
1642
+
1643
+ ---
1644
+
1645
+ <a name="modules--no-webpack-loader-syntax"></a>
1646
+ [**11.6**](#modules--no-webpack-loader-syntax) ‣ Disallow Webpack loader syntax in module import statements.
1647
+
1648
+ <img src="../eslint.svg" height="18" align="center"/> [`import/no-webpack-loader-syntax`](https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-webpack-loader-syntax.md)
1649
+
1650
+ > Why? Since using Webpack syntax in the imports couples the code to a module bundler. Prefer using the loader syntax in `webpack.config.js`.
1651
+
1652
+ ```typescript
1653
+ // bad
1654
+ import fooSass from 'css!sass!foo.scss';
1655
+ import barCss from 'style!css!bar.css';
1656
+
1657
+ // good
1658
+ import fooSass from 'foo.scss';
1659
+ import barCss from 'bar.css';
1660
+ ```
1661
+
1662
+ ---
1663
+
1664
+ <a name="modules--import-extensions"></a>
1665
+ [**11.7**](#modules--import-extensions) ‣ Do not include JavaScript filename extensions
1666
+
1667
+ <img src="../eslint.svg" height="18" align="center"/> [`import/extensions`](https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/extensions.md)
1668
+
1669
+ > Why? Including extensions inhibits refactoring, and inappropriately hardcodes implementation details of the module you're importing in every consumer.
1670
+
1671
+ ```typescript
1672
+ // bad
1673
+ import foo from './foo.js';
1674
+ import bar from './bar.jsx';
1675
+ import baz from './baz/index.jsx';
1676
+
1677
+ // good
1678
+ import foo from './foo';
1679
+ import bar from './bar';
1680
+ import baz from './baz';
1681
+ ```
1682
+
1683
+ **[⬆ back to top](#table-of-contents)**
1684
+
1685
+ ## Iterators and Generators
1686
+
1687
+ <a name="iterators--prefer-functional"></a>
1688
+ [**12.1**](#iterators--prefer-functional) ‣ Prefer JavaScript’s higher-order functions instead of `for`/`for-of` loops, particularly when iterating to build up a value.
1689
+
1690
+ > Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.
1691
+
1692
+ > Sometimes you genuinely will need to mutate or do something side-effecty in a loop, and in that case `for-of` or a traditional `for` loop are acceptable. But avoid this whenerever possible.
1693
+
1694
+ > Use `map()` / `every()` / `filter()` / `find()` / `findIndex()` / `reduce()` / `some()` / ... to iterate over arrays, and `Object.keys()` / `Object.values()` / `Object.entries()` to produce arrays so you can iterate over objects.
1695
+
1696
+ ```typescript
1697
+ const numbers = [1, 2, 3, 4, 5];
1698
+
1699
+ // bad
1700
+ let sum = 0;
1701
+ for (let num of numbers) {
1702
+ sum += num;
1703
+ }
1704
+ sum === 15;
1705
+
1706
+ // bad
1707
+ let sum = 0;
1708
+ numbers.forEach((num) => {
1709
+ sum += num;
1710
+ });
1711
+ sum === 15;
1712
+
1713
+ // good
1714
+ const sum = numbers.reduce((total, num) => total + num, 0);
1715
+ sum === 15;
1716
+
1717
+ // bad
1718
+ const increasedByOne = [];
1719
+ for (let i = 0; i < numbers.length; i++) {
1720
+ increasedByOne.push(numbers[i] + 1);
1721
+ }
1722
+
1723
+ // bad
1724
+ const increasedByOne = [];
1725
+ numbers.forEach((num) => {
1726
+ increasedByOne.push(num + 1);
1727
+ });
1728
+
1729
+ // good
1730
+ const increasedByOne = numbers.map((num) => num + 1);
1731
+ ```
1732
+
1733
+ ---
1734
+
1735
+ <a name="iterators--no-for-in"></a>
1736
+ [**12.2**](#iterators--no-for-in) ‣ Do not use `for-in`.
1737
+
1738
+ <img src="../eslint.svg" height="18" align="center"/> [`no-restricted-syntax`](https://eslint.org/docs/rules/no-restricted-syntax)
1739
+
1740
+ > Why? `for-in` has confusing and unexpected behavior. For this reason, `for-of` was added to the language and should be used instead.
1741
+
1742
+ ```typescript
1743
+ const obj = { a: 'foo', b: 'bar' };
1744
+
1745
+ // bad
1746
+ for (const key in obj) {
1747
+ console.log(key, obj[key]);
1748
+ }
1749
+
1750
+ // avoids the inherited properties issue, but still bad
1751
+ for (const key in obj) {
1752
+ if (obj.hasOwnProperty(key)) {
1753
+ console.log(key, obj[key]);
1754
+ }
1755
+ }
1756
+
1757
+ // good
1758
+ for (const key of Object.keys(obj)) {
1759
+ console.log(key, obj[key]);
1760
+ }
1761
+
1762
+ // best, if you're working on both the keys and values
1763
+ for (const [key, value] of Object.entries(obj)) {
1764
+ console.log(key, value);
1765
+ }
1766
+ ```
1767
+
1768
+ ---
1769
+
1770
+ <a name="generators--spacing"></a>
1771
+ [**12.3**](#generators--spacing) ‣ A generator's function signature should be spaced with `function*` as a single unit surrounded by spaces.
1772
+
1773
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
1774
+
1775
+ <img src="../eslint.svg" height="18" align="center"/> [`generator-star-spacing`](https://eslint.org/docs/rules/generator-star-spacing)
1776
+
1777
+ > Why? `function` and `*` are part of the same conceptual keyword - `*` is not a modifier for `function`, `function*` is a unique construct, different from `function`.
1778
+
1779
+ ```typescript
1780
+ // bad
1781
+ function * foo() {
1782
+ // ...
1783
+ }
1784
+
1785
+ // bad
1786
+ const bar = function * () {
1787
+ // ...
1788
+ };
1789
+
1790
+ // bad
1791
+ const baz = function *() {
1792
+ // ...
1793
+ };
1794
+
1795
+ // bad
1796
+ const quux = function*() {
1797
+ // ...
1798
+ };
1799
+
1800
+ // bad
1801
+ function*foo() {
1802
+ // ...
1803
+ }
1804
+
1805
+ // bad
1806
+ function *foo() {
1807
+ // ...
1808
+ }
1809
+
1810
+ // very bad
1811
+ function
1812
+ *
1813
+ foo() {
1814
+ // ...
1815
+ }
1816
+
1817
+ // very bad
1818
+ const wat = function
1819
+ *
1820
+ () {
1821
+ // ...
1822
+ };
1823
+
1824
+ // good
1825
+ function* foo() {
1826
+ // ...
1827
+ }
1828
+
1829
+ // good
1830
+ const foo = function* () {
1831
+ // ...
1832
+ };
1833
+ ```
1834
+
1835
+ **[⬆ back to top](#table-of-contents)**
1836
+
1837
+ ## Properties
1838
+
1839
+ <a name="properties--dot"></a>
1840
+ [**13.1**](#properties--dot) ‣ Use dot notation when accessing properties.
1841
+
1842
+ <img src="../eslint.svg" height="18" align="center"/> [`dot-notation`](https://eslint.org/docs/rules/dot-notation.html)
1843
+
1844
+ ```typescript
1845
+ const luke = {
1846
+ jedi: true,
1847
+ age: 28,
1848
+ };
1849
+
1850
+ // bad
1851
+ const isJedi = luke['jedi'];
1852
+
1853
+ // good
1854
+ const isJedi = luke.jedi;
1855
+ ```
1856
+
1857
+
1858
+ **[⬆ back to top](#table-of-contents)**
1859
+
1860
+ ## Variables
1861
+
1862
+ <a name="variables--const"></a>
1863
+ [**14.1**](#variables--const) ‣ Always use `const` or `let` to declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace. Captain Planet warned us of that.
1864
+
1865
+ <img src="../eslint.svg" height="18" align="center"/> [`no-undef`](https://eslint.org/docs/rules/no-undef), [`prefer-const`](https://eslint.org/docs/rules/prefer-const)
1866
+
1867
+ ```typescript
1868
+ // bad
1869
+ superPower = new SuperPower();
1870
+
1871
+ // good
1872
+ const superPower = new SuperPower();
1873
+ ```
1874
+
1875
+ ---
1876
+
1877
+ <a name="variables--one-const"></a>
1878
+ [**14.2**](#variables--one-const) ‣ Use one `const` or `let` declaration per variable or assignment.
1879
+
1880
+ <img src="../eslint.svg" height="18" align="center"/> [`one-var`](https://eslint.org/docs/rules/one-var.html)
1881
+
1882
+ > Why? It’s easier to add new variable declarations this way, and you never have to worry about swapping out a `;` for a `,` or introducing punctuation-only diffs. You can also step through each declaration with the debugger, instead of jumping through all of them at once.
1883
+
1884
+ ```typescript
1885
+ // bad
1886
+ const items = getItems(),
1887
+ goSportsTeam = true,
1888
+ dragonball = 'z';
1889
+
1890
+ // bad
1891
+ // (compare to above, and try to spot the mistake)
1892
+ const items = getItems(),
1893
+ goSportsTeam = true;
1894
+ dragonball = 'z';
1895
+
1896
+ // good
1897
+ const items = getItems();
1898
+ const goSportsTeam = true;
1899
+ const dragonball = 'z';
1900
+ ```
1901
+
1902
+ ---
1903
+
1904
+ <a name="variables--const-let-group"></a>
1905
+ [**14.3**](#variables--const-let-group) ‣ Group all your `const`s and then group all your `let`s.
1906
+
1907
+ > Why? This is helpful when later on you might need to assign a variable depending on one of the previously assigned variables.
1908
+
1909
+ ```typescript
1910
+ // bad
1911
+ let i, len, dragonball,
1912
+ items = getItems(),
1913
+ goSportsTeam = true;
1914
+
1915
+ // bad
1916
+ let i: number;
1917
+ const items = getItems();
1918
+ let dragonball: Dragonball;
1919
+ const goSportsTeam = true;
1920
+ let len: number;
1921
+
1922
+ // good
1923
+ const goSportsTeam = true;
1924
+ const items = getItems();
1925
+ let dragonball: Dragonball;
1926
+ let i: number;
1927
+ let length: number;
1928
+ ```
1929
+
1930
+ ---
1931
+
1932
+ <a name="variables--define-where-used"></a>
1933
+ [**14.4**](#variables--define-where-used) ‣ Assign variables where you need them, but place them in a reasonable place.
1934
+
1935
+ > Why? `let` and `const` are block scoped and not function scoped.
1936
+
1937
+ ```typescript
1938
+ // bad - unnecessary function call
1939
+ function checkName(hasName) {
1940
+ const name = getName();
1941
+
1942
+ if (hasName === 'test') {
1943
+ return false;
1944
+ }
1945
+
1946
+ if (name === 'test') {
1947
+ this.setName('');
1948
+ return false;
1949
+ }
1950
+
1951
+ return name;
1952
+ }
1953
+
1954
+ // good
1955
+ function checkName(hasName) {
1956
+ if (hasName === 'test') {
1957
+ return false;
1958
+ }
1959
+
1960
+ const name = getName();
1961
+
1962
+ if (name === 'test') {
1963
+ this.setName('');
1964
+ return false;
1965
+ }
1966
+
1967
+ return name;
1968
+ }
1969
+ ```
1970
+
1971
+ <a name="variables--no-chain-assignment"></a>
1972
+ [**14.5**](#variables--no-chain-assignment) ‣ Don’t chain variable assignments.
1973
+
1974
+ <img src="../eslint.svg" height="18" align="center"/> [`no-multi-assign`](https://eslint.org/docs/rules/no-multi-assign)
1975
+
1976
+ > Why? Chaining variable assignments creates implicit global variables.
1977
+
1978
+ ```typescript
1979
+ // bad
1980
+ (function example() {
1981
+ // JavaScript interprets this as
1982
+ // let a = ( b = ( c = 1 ) );
1983
+ // The let keyword only applies to variable a; variables b and c become
1984
+ // global variables.
1985
+ let a = b = c = 1;
1986
+ }());
1987
+
1988
+ console.log(a); // throws ReferenceError
1989
+ console.log(b); // 1
1990
+ console.log(c); // 1
1991
+
1992
+ // good
1993
+ (function example() {
1994
+ let a = 1;
1995
+ let b = a;
1996
+ let c = a;
1997
+ }());
1998
+
1999
+ console.log(a); // throws ReferenceError
2000
+ console.log(b); // throws ReferenceError
2001
+ console.log(c); // throws ReferenceError
2002
+
2003
+ // the same applies for `const`
2004
+ ```
2005
+
2006
+ ---
2007
+
2008
+ <a name="variables--unary-increment-decrement"></a>
2009
+ [**14.6**](#variables--unary-increment-decrement) ‣ Avoid using unary increments and decrements (`++`, `--`).
2010
+
2011
+ <img src="../eslint.svg" height="18" align="center"/> [`no-plusplus`](https://eslint.org/docs/rules/no-plusplus)
2012
+
2013
+ > Why? Per the eslint documentation, unary increment and decrement statements are subject to automatic semicolon insertion and can cause silent errors with incrementing or decrementing values within an application. It is also more expressive to mutate your values with statements like `num += 1` instead of `num++` or `num ++`. Disallowing unary increment and decrement statements also prevents you from pre-incrementing/pre-decrementing values unintentionally which can also cause unexpected behavior in your programs.
2014
+
2015
+ ```typescript
2016
+ // bad
2017
+
2018
+ const array = [1, 2, 3];
2019
+ let num = 1;
2020
+ num++;
2021
+ --num;
2022
+
2023
+ let sum = 0;
2024
+ let truthyCount = 0;
2025
+ for (let i = 0; i < array.length; i++) {
2026
+ let value = array[i];
2027
+ sum += value;
2028
+ if (value) {
2029
+ truthyCount++;
2030
+ }
2031
+ }
2032
+
2033
+ // good
2034
+
2035
+ const array = [1, 2, 3];
2036
+ let num = 1;
2037
+ num += 1;
2038
+ num -= 1;
2039
+
2040
+ const sum = array.reduce((a, b) => a + b, 0);
2041
+ const truthyCount = array.filter(Boolean).length;
2042
+ ```
2043
+
2044
+ ---
2045
+
2046
+ <a name="variables--linebreak"></a>
2047
+ [**14.7**](#variables--linebreak) ‣ Avoid linebreaks before or after `=` in an assignment. If your assignment violates [`max-len`](https://eslint.org/docs/rules/max-len.html), surround the value in parens.
2048
+
2049
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
2050
+
2051
+ > Why? Linebreaks surrounding `=` can obfuscate the value of an assignment.
2052
+
2053
+ ```typescript
2054
+ // bad
2055
+ const foo =
2056
+ superLongLongLongLongLongLongLongLongFunctionName();
2057
+
2058
+ // bad
2059
+ const foo
2060
+ = 'superLongLongLongLongLongLongLongLongString';
2061
+
2062
+ // good
2063
+ const foo = (
2064
+ superLongLongLongLongLongLongLongLongFunctionName()
2065
+ );
2066
+
2067
+ // good
2068
+ const foo = 'superLongLongLongLongLongLongLongLongString';
2069
+ ```
2070
+
2071
+ ---
2072
+
2073
+ <a name="variables--no-unused-vars"></a>
2074
+ [**14.8**](#variables--no-unused-vars) ‣ Disallow unused variables.
2075
+
2076
+ <img src="../eslint.svg" height="18" align="center"/> [`no-unused-vars`](https://eslint.org/docs/rules/no-unused-vars)
2077
+
2078
+ > Why? Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such variables take up space in the code and can lead to confusion by readers.
2079
+
2080
+ ```typescript
2081
+ // bad
2082
+ const some_unused_var = 42;
2083
+
2084
+ // Write-only variables are not considered as used.
2085
+ let y = 10;
2086
+ y = 5;
2087
+
2088
+ // A read for a modification of itself is not considered as used.
2089
+ let z = 0;
2090
+ z = z + 1;
2091
+
2092
+ // Unused function arguments.
2093
+ function getX(x: number, y: number): number {
2094
+ return x;
2095
+ }
2096
+
2097
+ // good
2098
+ function getXPlusY(x: number, y: number): number {
2099
+ return x + y;
2100
+ }
2101
+
2102
+ const x = 1;
2103
+ const y = a + 2;
2104
+
2105
+ alert(getXPlusY(x, y));
2106
+
2107
+ // 'type' is ignored even if unused because it has a rest property sibling.
2108
+ // This is a form of extracting an object that omits the specified keys.
2109
+ const { type, ...coords } = data;
2110
+ // 'coords' is now the 'data' object without its 'type' property.
2111
+ ```
2112
+
2113
+ **[⬆ back to top](#table-of-contents)**
2114
+
2115
+
2116
+ ## Comparison Operators & Equality
2117
+
2118
+ <a name="comparison--eqeqeq"></a>
2119
+ [**15.1**](#comparison--eqeqeq) ‣ Use `===` and `!==` over `==` and `!=`.
2120
+
2121
+ <img src="../eslint.svg" height="18" align="center"/> [`eqeqeq`](https://eslint.org/docs/rules/eqeqeq.html)
2122
+
2123
+ ---
2124
+
2125
+ <a name="comparison--if"></a>
2126
+ 💡 [**15.2**](#comparison--if) ‣ Conditional statements such as the `if` statement evaluate their expression using coercion with the `ToBoolean` abstract method and always follow these simple rules:
2127
+
2128
+ - **Objects** evaluate to **true**
2129
+ - **Undefined** evaluates to **false**
2130
+ - **Null** evaluates to **false**
2131
+ - **Booleans** evaluate to **the value of the boolean**
2132
+ - **Numbers** evaluate to **false** if **+0, -0, or NaN**, otherwise **true**
2133
+ - **Strings** evaluate to **false** if an empty string `''`, otherwise **true**
2134
+
2135
+ ```typescript
2136
+ if ([0] && []) {
2137
+ // true
2138
+ // an array (even an empty one) is an object, objects will evaluate to true
2139
+ }
2140
+ ```
2141
+
2142
+ ---
2143
+
2144
+ <a name="comparison--shortcuts"></a>
2145
+ [**15.3**](#comparison--shortcuts) ‣ Use shortcuts for booleans, but explicit comparisons for strings and numbers.
2146
+
2147
+ ```typescript
2148
+ // bad
2149
+ if (isValid === true) {
2150
+ // ...
2151
+ }
2152
+
2153
+ // good
2154
+ if (isValid) {
2155
+ // ...
2156
+ }
2157
+
2158
+ // bad
2159
+ if (name) {
2160
+ // ...
2161
+ }
2162
+
2163
+ // good
2164
+ if (name !== '') {
2165
+ // ...
2166
+ }
2167
+
2168
+ // bad
2169
+ if (collection.length) {
2170
+ // ...
2171
+ }
2172
+
2173
+ // good
2174
+ if (collection.length > 0) {
2175
+ // ...
2176
+ }
2177
+ ```
2178
+
2179
+ ---
2180
+
2181
+ <a name="comparison--moreinfo"></a>
2182
+ 💡 [**15.4**](#comparison--moreinfo) ‣ For more information, see [Truth Equality and JavaScript](https://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/#more-2108) by Angus Croll.
2183
+
2184
+ ---
2185
+
2186
+ <a name="comparison--switch-blocks"></a>
2187
+ [**15.5**](#comparison--switch-blocks) ‣ In switch statements, use braces to create blocks for all `case` and `default` clauses, or none of them. Be consistent.
2188
+
2189
+ ```typescript
2190
+ // bad
2191
+ switch (foo) {
2192
+ case 1:
2193
+ // ...
2194
+ break;
2195
+ case 2: {
2196
+ // ...
2197
+ break;
2198
+ }
2199
+ case 3:
2200
+ // ...
2201
+ break;
2202
+ default: {
2203
+ // ...
2204
+ }
2205
+ }
2206
+
2207
+ // good
2208
+ switch (foo) {
2209
+ case 1:
2210
+ // ...
2211
+ break;
2212
+ case 2:
2213
+ // ...
2214
+ break;
2215
+ case 3:
2216
+ // ...
2217
+ break;
2218
+ default:
2219
+ // ...
2220
+ }
2221
+
2222
+ // good
2223
+ switch (foo) {
2224
+ case 1: {
2225
+ // ...
2226
+ break;
2227
+ }
2228
+ case 2: {
2229
+ // ...
2230
+ break;
2231
+ }
2232
+ case 3: {
2233
+ // ...
2234
+ break;
2235
+ }
2236
+ default: {
2237
+ // ...
2238
+ }
2239
+ }
2240
+ ```
2241
+
2242
+ ---
2243
+
2244
+ <a name="comparison--nested-ternaries"></a>
2245
+ [**15.6**](#comparison--nested-ternaries) ‣ Ternaries should not be nested and generally be single line expressions.
2246
+
2247
+ <img src="../eslint.svg" height="18" align="center"/> [`no-nested-ternary`](https://eslint.org/docs/rules/no-nested-ternary.html)
2248
+
2249
+ ```typescript
2250
+ // bad
2251
+ const foo = maybe1 > maybe2
2252
+ ? "bar"
2253
+ : value1 > value2 ? "baz" : null;
2254
+
2255
+ // split into 2 separated ternary expressions
2256
+ const maybeNull = value1 > value2 ? 'baz' : null;
2257
+
2258
+ // better
2259
+ const foo = maybe1 > maybe2
2260
+ ? 'bar'
2261
+ : maybeNull;
2262
+
2263
+ // best
2264
+ const foo = maybe1 > maybe2 ? 'bar' : maybeNull;
2265
+ ```
2266
+
2267
+ ---
2268
+
2269
+ <a name="comparison--unneeded-ternary"></a>
2270
+ [**15.7**](#comparison--unneeded-ternary) ‣ Avoid unneeded ternary statements.
2271
+
2272
+ <img src="../eslint.svg" height="18" align="center"/> [`no-unneeded-ternary`](https://eslint.org/docs/rules/no-unneeded-ternary.html)
2273
+
2274
+ ```typescript
2275
+ // bad
2276
+ const bar = c ? true : false;
2277
+ const baz = c ? false : true;
2278
+
2279
+ // good
2280
+ const bar = !!c;
2281
+ const baz = !c;
2282
+ ```
2283
+
2284
+ ---
2285
+
2286
+ <a name="comparison--no-mixed-operators"></a>
2287
+ [**15.8**](#comparison--no-mixed-operators) ‣ When mixing operators, enclose them in parentheses. The only exception is the standard arithmetic operators: `+`, `-`, and `**` since their precedence is broadly understood. We recommend enclosing `/` and `*` in parentheses because their precedence can be ambiguous when they are mixed.
2288
+
2289
+ <img src="../eslint.svg" height="18" align="center"/> [`no-mixed-operators`](https://eslint.org/docs/rules/no-mixed-operators.html)
2290
+
2291
+ > Why? This improves readability and clarifies the developer’s intention.
2292
+
2293
+ ```typescript
2294
+ // bad
2295
+ const foo = a && b < 0 || c > 0 || d + 1 === 0;
2296
+
2297
+ // bad
2298
+ const bar = a ** b - 5 % d;
2299
+
2300
+ // bad
2301
+ // one may be confused into thinking (a || b) && c
2302
+ if (a || b && c) {
2303
+ return d;
2304
+ }
2305
+
2306
+ // bad
2307
+ const bar = a + b / c * d;
2308
+
2309
+ // good
2310
+ const foo = (a && b < 0) || c > 0 || (d + 1 === 0);
2311
+
2312
+ // good
2313
+ const bar = a ** b - (5 % d);
2314
+
2315
+ // good
2316
+ if (a || (b && c)) {
2317
+ return d;
2318
+ }
2319
+
2320
+ // good
2321
+ const bar = a + (b / c) * d;
2322
+ ```
2323
+
2324
+ ---
2325
+
2326
+ <a name="comparison--nullish-coalescing"></a>
2327
+ [**15.9**](#comparison--nullish-coalescing) ‣ Use the nullish coalescing operator over `||`. If you do need to coalesce over a falsy value that is not `null` or `undefined`, use a ternary that defines the desired condition explicitly.
2328
+
2329
+ <img src="../eslint.svg" height="18" align="center"/> [`@typescript-eslint/prefer-nullish-coalescing`](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/prefer-nullish-coalescing.md)
2330
+
2331
+ ```typescript
2332
+ // bad
2333
+ const foo = bar || "baz";
2334
+
2335
+ // good
2336
+ const foo = bar ?? "baz";
2337
+
2338
+ // or, if empty string should actually fall through to "baz"...
2339
+ const foo = typeof foo === "string" && foo !== "" ? foo : "baz";
2340
+ ```
2341
+
2342
+ **[⬆ back to top](#table-of-contents)**
2343
+
2344
+ ## Blocks
2345
+
2346
+ <a name="blocks--cuddled-elses"></a>
2347
+ [**16.1**](#blocks--cuddled-elses) ‣ If you’re using multiline blocks with `if` and `else`, put `else` on the same line as your `if` block’s closing brace.
2348
+
2349
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
2350
+
2351
+ <img src="../eslint.svg" height="18" align="center"/> [`brace-style`](https://eslint.org/docs/rules/brace-style.html)
2352
+
2353
+ ```typescript
2354
+ // bad
2355
+ if (test) {
2356
+ thing1();
2357
+ thing2();
2358
+ }
2359
+ else {
2360
+ thing3();
2361
+ }
2362
+
2363
+ // good
2364
+ if (test) {
2365
+ thing1();
2366
+ thing2();
2367
+ } else {
2368
+ thing3();
2369
+ }
2370
+ ```
2371
+
2372
+ **[⬆ back to top](#table-of-contents)**
2373
+
2374
+ ## Control Statements
2375
+
2376
+ <a name="control-statements"></a>
2377
+ [**17.1**](#control-statements) ‣ In case your control statement (`if`, `while` etc.) gets too long or exceeds the maximum line length, each (grouped) condition could be put into a new line.
2378
+
2379
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
2380
+
2381
+ > Why? This improves readability by making it easier to visually follow complex logic.
2382
+
2383
+ ```typescript
2384
+ // bad
2385
+ if ((foo === 123 || bar === 'abc') && doesItLookGoodWhenItBecomesThatLong() && isThisReallyHappening()) {
2386
+ thing1();
2387
+ }
2388
+
2389
+ // bad
2390
+ if ((foo === 123 || bar === 'abc') &&
2391
+ doesItLookGoodWhenItBecomesThatLong() &&
2392
+ isThisReallyHappening()) {
2393
+ thing1();
2394
+ }
2395
+
2396
+ // good
2397
+ if (
2398
+ (foo === 123 || bar === 'abc') &&
2399
+ doesItLookGoodWhenItBecomesThatLong() &&
2400
+ isThisReallyHappening()
2401
+ ) {
2402
+ thing1();
2403
+ }
2404
+
2405
+ // good
2406
+ if (
2407
+ (foo === 123 ||
2408
+ bar === 'abc' ||
2409
+ someOtherReallyLongFunctionName()) &&
2410
+ doesItLookGoodWhenItBecomesThatLong() &&
2411
+ isThisReallyHappening()
2412
+ ) {
2413
+ thing1();
2414
+ }
2415
+
2416
+ // good
2417
+ if (foo === 123 && bar === 'abc') {
2418
+ thing1();
2419
+ }
2420
+ ```
2421
+
2422
+ ---
2423
+
2424
+ <a name="control-statements--value-selection"></a>
2425
+ [**17.2**](#control-statements--value-selection) ‣ Don't use selection operators in place of control statements.
2426
+
2427
+ ```typescript
2428
+ // bad
2429
+ !isRunning && startRunning();
2430
+
2431
+ // good
2432
+ if (!isRunning) {
2433
+ startRunning();
2434
+ }
2435
+ ```
2436
+
2437
+ ---
2438
+
2439
+ <a name="control-statements--no-labeled-statements"></a>
2440
+ [**17.3**](#control-statements--value-selection) ‣ Don't use labeled statements. Labels are a form of GOTO; using them makes code confusing and hard to maintain and understand.
2441
+
2442
+ **[⬆ back to top](#table-of-contents)**
2443
+
2444
+ ## Comments
2445
+
2446
+ <a name="comments--multiline"></a>
2447
+ [**18.1**](#comments--multiline) ‣ Use `/** ... */` for multiline comments.
2448
+
2449
+ ```typescript
2450
+ // bad
2451
+ // make() returns a new element
2452
+ // based on the passed in tag name
2453
+ function make(tag: string): Element {
2454
+
2455
+ // ...
2456
+
2457
+ return element;
2458
+ }
2459
+
2460
+ // good
2461
+ /**
2462
+ * make() returns a new element
2463
+ * based on the passed-in tag name
2464
+ */
2465
+ function make(tag: string): Element {
2466
+
2467
+ // ...
2468
+
2469
+ return element;
2470
+ }
2471
+ ```
2472
+
2473
+ ---
2474
+
2475
+ <a name="comments--singleline"></a>
2476
+ [**18.2**](#comments--singleline) ‣ Use `//` for single line comments. Place single line comments on a newline above the subject of the comment. Put an empty line before the comment unless it’s on the first line of a block.
2477
+
2478
+ ```typescript
2479
+ // bad
2480
+ const active = true; // is current tab
2481
+
2482
+ // good
2483
+ // is current tab
2484
+ const active = true;
2485
+
2486
+ // bad
2487
+ function getType() {
2488
+ console.log('fetching type...');
2489
+ // set the default type to 'no type'
2490
+ const type = this.type || 'no type';
2491
+
2492
+ return type;
2493
+ }
2494
+
2495
+ // good
2496
+ function getType() {
2497
+ console.log('fetching type...');
2498
+
2499
+ // set the default type to 'no type'
2500
+ const type = this.type || 'no type';
2501
+
2502
+ return type;
2503
+ }
2504
+
2505
+ // also good
2506
+ function getType() {
2507
+ // set the default type to 'no type'
2508
+ const type = this.type || 'no type';
2509
+
2510
+ return type;
2511
+ }
2512
+ ```
2513
+
2514
+ ---
2515
+
2516
+ <a name="comments--spaces"></a>
2517
+ [**18.3**](#comments--spaces) ‣ Start all comments with a space to make it easier to read.
2518
+
2519
+ <img src="../eslint.svg" height="18" align="center"/> [`spaced-comment`](https://eslint.org/docs/rules/spaced-comment)
2520
+
2521
+ ```typescript
2522
+ // bad
2523
+ //is current tab
2524
+ const active = true;
2525
+
2526
+ // good
2527
+ // is current tab
2528
+ const active = true;
2529
+
2530
+ // bad
2531
+ /**
2532
+ *make() returns a new element
2533
+ *based on the passed-in tag name
2534
+ */
2535
+ function make(tag: string): Element {
2536
+
2537
+ // ...
2538
+
2539
+ return element;
2540
+ }
2541
+
2542
+ // good
2543
+ /**
2544
+ * make() returns a new element
2545
+ * based on the passed-in tag name
2546
+ */
2547
+ function make(tag: string): Element {
2548
+
2549
+ // ...
2550
+
2551
+ return element;
2552
+ }
2553
+ ```
2554
+
2555
+ ---
2556
+
2557
+ <a name="comments--actionitems"></a>
2558
+ 💡 [**18.4**](#comments--actionitems) ‣ Prefixing your comments with `FIXME` or `TODO` helps other developers quickly understand if you’re pointing out a problem that needs to be revisited, or if you’re suggesting a solution to the problem that needs to be implemented. These are different than regular comments because they are actionable. The actions are `FIXME: -- need to figure this out` or `TODO: -- need to implement`.
2559
+
2560
+ ```typescript
2561
+ class Calculator extends Abacus {
2562
+ constructor() {
2563
+ super();
2564
+
2565
+ // FIXME: shouldn’t use a global here
2566
+ total = 0;
2567
+ }
2568
+ }
2569
+ ```
2570
+
2571
+ ```typescript
2572
+ class Calculator extends Abacus {
2573
+ constructor() {
2574
+ super();
2575
+
2576
+ // TODO: total should be configurable by an options param
2577
+ this.total = 0;
2578
+ }
2579
+ }
2580
+ ```
2581
+
2582
+ **[⬆ back to top](#table-of-contents)**
2583
+
2584
+ ## Whitespace
2585
+
2586
+ <a name="whitespace--spaces"></a>
2587
+ [**19.1**](#whitespace--spaces) ‣ Use soft tabs (space character) set to 2 spaces.
2588
+
2589
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
2590
+
2591
+ <img src="../eslint.svg" height="18" align="center"/> [`indent`](https://eslint.org/docs/rules/indent.html)
2592
+
2593
+ ```typescript
2594
+ // bad
2595
+ function foo() {
2596
+ ∙∙∙∙let name;
2597
+ }
2598
+
2599
+ // bad
2600
+ function bar() {
2601
+ ∙let name;
2602
+ }
2603
+
2604
+ // good
2605
+ function baz() {
2606
+ ∙∙let name;
2607
+ }
2608
+ ```
2609
+
2610
+ ---
2611
+
2612
+ <a name="whitespace--before-blocks"></a>
2613
+ [**19.2**](#whitespace--before-blocks) ‣ Place 1 space before the leading brace.
2614
+
2615
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
2616
+
2617
+ <img src="../eslint.svg" height="18" align="center"/> [`space-before-blocks`](https://eslint.org/docs/rules/space-before-blocks.html)
2618
+
2619
+ ```typescript
2620
+ // bad
2621
+ function test(){
2622
+ console.log('test');
2623
+ }
2624
+
2625
+ // good
2626
+ function test() {
2627
+ console.log('test');
2628
+ }
2629
+
2630
+ // bad
2631
+ dog.set('attr',{
2632
+ age: '1 year',
2633
+ breed: 'Bernese Mountain Dog',
2634
+ });
2635
+
2636
+ // good
2637
+ dog.set('attr', {
2638
+ age: '1 year',
2639
+ breed: 'Bernese Mountain Dog',
2640
+ });
2641
+ ```
2642
+
2643
+ ---
2644
+
2645
+ <a name="whitespace--around-keywords"></a>
2646
+ [**19.3**](#whitespace--around-keywords) ‣ Place 1 space before the opening parenthesis in control statements (`if`, `while` etc.). Place no space between the argument list and the function name in function calls and declarations.
2647
+
2648
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
2649
+
2650
+ <img src="../eslint.svg" height="18" align="center"/> [`keyword-spacing`](https://eslint.org/docs/rules/keyword-spacing.html)
2651
+
2652
+ ```typescript
2653
+ // bad
2654
+ if(isJedi) {
2655
+ fight ();
2656
+ }
2657
+
2658
+ // good
2659
+ if (isJedi) {
2660
+ fight();
2661
+ }
2662
+
2663
+ // bad
2664
+ function fight () {
2665
+ console.log ('Swooosh!');
2666
+ }
2667
+
2668
+ // good
2669
+ function fight() {
2670
+ console.log('Swooosh!');
2671
+ }
2672
+ ```
2673
+
2674
+ ---
2675
+
2676
+ <a name="whitespace--infix-ops"></a>
2677
+ [**19.4**](#whitespace--infix-ops) ‣ Set off operators with spaces.
2678
+
2679
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
2680
+
2681
+ <img src="../eslint.svg" height="18" align="center"/> [`space-infix-ops`](https://eslint.org/docs/rules/space-infix-ops.html)
2682
+
2683
+ ```typescript
2684
+ // bad
2685
+ const x=y+5;
2686
+
2687
+ // good
2688
+ const x = y + 5;
2689
+ ```
2690
+
2691
+ ---
2692
+
2693
+ <a name="whitespace--newline-at-end"></a>
2694
+ [**19.5**](#whitespace--newline-at-end) ‣ End files with a single newline character.
2695
+
2696
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
2697
+
2698
+ <img src="../eslint.svg" height="18" align="center"/> [`eol-last`](https://github.com/eslint/eslint/blob/master/docs/rules/eol-last.md)
2699
+
2700
+ ```typescript
2701
+ // bad
2702
+ import { es6 } from './AirbnbStyleGuide';
2703
+ // ...
2704
+ export default es6;
2705
+ ```
2706
+
2707
+ ```typescript
2708
+ // bad
2709
+ import { es6 } from './AirbnbStyleGuide';
2710
+ // ...
2711
+ export default es6;↵
2712
+
2713
+ ```
2714
+
2715
+ ```typescript
2716
+ // good
2717
+ import { es6 } from './AirbnbStyleGuide';
2718
+ // ...
2719
+ export default es6;↵
2720
+ ```
2721
+
2722
+ ---
2723
+
2724
+ <a name="whitespace--chains"></a>
2725
+ [**19.6**](#whitespace--chains) ‣ Use indentation when making long method chains (more than 2 method chains). Use a leading dot, which emphasizes that the line is a method call, not a new statement.
2726
+
2727
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
2728
+
2729
+ <img src="../eslint.svg" height="18" align="center"/> [`newline-per-chained-call`](https://eslint.org/docs/rules/newline-per-chained-call), [`no-whitespace-before-property`](https://eslint.org/docs/rules/no-whitespace-before-property)
2730
+
2731
+ ```typescript
2732
+ // bad
2733
+ const foo = bar.qwer('.baz').tyui(data).op().asdf('beep').ghjkl('baz', true)
2734
+ .zxc('substance', (ecto + plasm) * 2).asdf('green').
2735
+ zxc('try', `contain(${ecto + plasm}, ${ecto + plasm})`)
2736
+ .call(tron.baz);
2737
+
2738
+ // good
2739
+ const foo = bar
2740
+ .qwer('.baz')
2741
+ .tyui(data)
2742
+ .op()
2743
+ .asdf('beep')
2744
+ .ghjkl('baz', true)
2745
+ .zxc('substance', (ecto + plasm) * 2)
2746
+ .asdf('green')
2747
+ .zxc('try', `contain(${ecto + plasm}, ${ecto + plasm})`)
2748
+ .call(tron.baz);
2749
+ ```
2750
+
2751
+ ---
2752
+
2753
+ <a name="whitespace--after-blocks"></a>
2754
+ [**19.7**](#whitespace--after-blocks) ‣ Leave a blank line after blocks and before the next statement.
2755
+
2756
+ ```typescript
2757
+ // bad
2758
+ if (foo) {
2759
+ return bar;
2760
+ }
2761
+ return baz;
2762
+
2763
+ // good
2764
+ if (foo) {
2765
+ return bar;
2766
+ }
2767
+
2768
+ return baz;
2769
+
2770
+ // bad
2771
+ const obj = {
2772
+ foo() {
2773
+ },
2774
+ bar() {
2775
+ },
2776
+ };
2777
+ return obj;
2778
+
2779
+ // good
2780
+ const obj = {
2781
+ foo() {
2782
+ },
2783
+
2784
+ bar() {
2785
+ },
2786
+ };
2787
+
2788
+ return obj;
2789
+
2790
+ // bad
2791
+ const arr = [
2792
+ function foo() {
2793
+ },
2794
+ function bar() {
2795
+ },
2796
+ ];
2797
+ return arr;
2798
+
2799
+ // good
2800
+ const arr = [
2801
+ function foo() {
2802
+ },
2803
+
2804
+ function bar() {
2805
+ },
2806
+ ];
2807
+
2808
+ return arr;
2809
+ ```
2810
+
2811
+ ---
2812
+
2813
+ <a name="whitespace--padded-blocks"></a>
2814
+ [**19.8**](#whitespace--padded-blocks) ‣ Do not pad your blocks with blank lines.
2815
+
2816
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
2817
+
2818
+ <img src="../eslint.svg" height="18" align="center"/> [`padded-blocks`](https://eslint.org/docs/rules/padded-blocks.html)
2819
+
2820
+ ```typescript
2821
+ // bad
2822
+ function bar() {
2823
+
2824
+ console.log(foo);
2825
+
2826
+ }
2827
+
2828
+ // bad
2829
+ if (baz) {
2830
+
2831
+ console.log(qux);
2832
+ } else {
2833
+ console.log(foo);
2834
+
2835
+ }
2836
+
2837
+ // bad
2838
+ class Foo {
2839
+ bar: Bar;
2840
+
2841
+ constructor(bar: Bar) {
2842
+ this.bar = bar;
2843
+ }
2844
+ }
2845
+
2846
+ // good
2847
+ function bar() {
2848
+ console.log(foo);
2849
+ }
2850
+
2851
+ // good
2852
+ if (baz) {
2853
+ console.log(qux);
2854
+ } else {
2855
+ console.log(foo);
2856
+ }
2857
+ ```
2858
+
2859
+ ---
2860
+
2861
+ <a name="whitespace--no-multiple-blanks"></a>
2862
+ [**19.9**](#whitespace--no-multiple-blanks) ‣ Do not use multiple blank lines to pad your code.
2863
+
2864
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
2865
+
2866
+ <img src="../eslint.svg" height="18" align="center"/> [`no-multiple-empty-lines`](https://eslint.org/docs/rules/no-multiple-empty-lines)
2867
+
2868
+ ```typescript
2869
+ // bad
2870
+ class Person {
2871
+ fullName: string;
2872
+ email: string;
2873
+ birthday: Date;
2874
+ age: number;
2875
+
2876
+ constructor(fullName: string, email: string, birthday: Date) {
2877
+ this.fullName = fullName;
2878
+
2879
+
2880
+ this.email = email;
2881
+
2882
+
2883
+ this.setAge(birthday);
2884
+ }
2885
+
2886
+
2887
+ setAge(birthday: Date) {
2888
+ const today = new Date();
2889
+
2890
+
2891
+ const age = this.getAge(today, birthday);
2892
+
2893
+
2894
+ this.age = age;
2895
+ }
2896
+
2897
+
2898
+ getAge(today: Date, birthday: Date): number {
2899
+ // ..
2900
+ }
2901
+ }
2902
+
2903
+ // good
2904
+ class Person {
2905
+ fullName: string;
2906
+ email: string;
2907
+ birthday: Date;
2908
+ age: number;
2909
+
2910
+ constructor(fullName: string, email: string, birthday: Date) {
2911
+ this.fullName = fullName;
2912
+ this.email = email;
2913
+ this.setAge(birthday);
2914
+ }
2915
+
2916
+ setAge(birthday: Date) {
2917
+ const today = new Date();
2918
+ const age = getAge(today, birthday);
2919
+ this.age = age;
2920
+ }
2921
+
2922
+ getAge(today: Date, birthday: Date): number {
2923
+ // ..
2924
+ }
2925
+ }
2926
+ ```
2927
+
2928
+ ---
2929
+
2930
+ <a name="whitespace--in-parens"></a>
2931
+ [**19.10**](#whitespace--in-parens) ‣ Do not add spaces inside parentheses.
2932
+
2933
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
2934
+
2935
+ <img src="../eslint.svg" height="18" align="center"/> [`space-in-parens`](https://eslint.org/docs/rules/space-in-parens.html)
2936
+
2937
+ ```typescript
2938
+ // bad
2939
+ function bar( foo ) {
2940
+ return foo;
2941
+ }
2942
+
2943
+ // good
2944
+ function bar(foo) {
2945
+ return foo;
2946
+ }
2947
+
2948
+ // bad
2949
+ if ( foo ) {
2950
+ console.log(foo);
2951
+ }
2952
+
2953
+ // good
2954
+ if (foo) {
2955
+ console.log(foo);
2956
+ }
2957
+ ```
2958
+
2959
+ ---
2960
+
2961
+ <a name="whitespace--in-brackets"></a>
2962
+ [**19.11**](#whitespace--in-brackets) ‣ Do not add spaces inside brackets.
2963
+
2964
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
2965
+
2966
+ <img src="../eslint.svg" height="18" align="center"/> [`array-bracket-spacing`](https://eslint.org/docs/rules/array-bracket-spacing.html)
2967
+
2968
+ ```typescript
2969
+ // bad
2970
+ const foo = [ 1, 2, 3 ];
2971
+ console.log(foo[ 0 ]);
2972
+
2973
+ // good
2974
+ const foo = [1, 2, 3];
2975
+ console.log(foo[0]);
2976
+ ```
2977
+
2978
+ ---
2979
+
2980
+ <a name="whitespace--in-braces"></a>
2981
+ [**19.12**](#whitespace--in-braces) ‣ Add spaces inside curly braces.
2982
+
2983
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
2984
+
2985
+ <img src="../eslint.svg" height="18" align="center"/> [`object-curly-spacing`](https://eslint.org/docs/rules/object-curly-spacing.html)
2986
+
2987
+ ```typescript
2988
+ // bad
2989
+ const foo = {clark: 'kent'};
2990
+
2991
+ // good
2992
+ const foo = { clark: 'kent' };
2993
+ ```
2994
+
2995
+ ---
2996
+
2997
+ <a name="whitespace--max-len"></a>
2998
+ [**19.13**](#whitespace--max-len) ‣ Avoid having lines of code that are longer than 100 characters (including whitespace). Note: per [above](#strings--line-length), long strings are exempt from this rule, and should not be broken up.
2999
+
3000
+ Prettier does not enforce this specifically, but will wrap lines at _roughly_ 80 characters, meaning that after it has done its formatting your code will - except in extremely rare circumstances - fit within the 100 character limit. Please refer to [Prettier's documentation on the print width option](https://prettier.io/docs/en/options.html#print-width) for more information.
3001
+
3002
+ <img src="../eslint.svg" height="18" align="center"/> [`max-len`](https://eslint.org/docs/rules/max-len.html)
3003
+
3004
+ > Why? This ensures readability and maintainability.
3005
+
3006
+ ```typescript
3007
+ // bad
3008
+ const foo = jsonData && jsonData.foo && jsonData.foo.bar && jsonData.foo.bar.baz && jsonData.foo.bar.baz.quux && jsonData.foo.bar.baz.quux.xyzzy;
3009
+
3010
+ // good
3011
+ const foo = jsonData
3012
+ && jsonData.foo
3013
+ && jsonData.foo.bar
3014
+ && jsonData.foo.bar.baz
3015
+ && jsonData.foo.bar.baz.quux
3016
+ && jsonData.foo.bar.baz.quux.xyzzy;
3017
+ ```
3018
+
3019
+ ---
3020
+
3021
+ <a name="whitespace--comma-spacing"></a>
3022
+ [**19.14**](#whitespace--comma-spacing) ‣ Avoid spaces before commas and require a space after commas.
3023
+
3024
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
3025
+
3026
+ <img src="../eslint.svg" height="18" align="center"/> [`comma-spacing`](https://eslint.org/docs/rules/comma-spacing)
3027
+
3028
+ ```typescript
3029
+ // bad
3030
+ const arr = [1 , 2];
3031
+
3032
+ // good
3033
+ const arr = [1, 2];
3034
+ ```
3035
+
3036
+ ---
3037
+
3038
+ <a name="whitespace--computed-property-spacing"></a>
3039
+ [**19.15**](#whitespace--computed-property-spacing) ‣ Enforce spacing inside of computed property brackets.
3040
+
3041
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
3042
+
3043
+ <img src="../eslint.svg" height="18" align="center"/> [`computed-property-spacing`](https://eslint.org/docs/rules/computed-property-spacing)
3044
+
3045
+ ```typescript
3046
+ // bad
3047
+ obj[foo ]
3048
+ obj[ 'foo']
3049
+ const x = {[ b ]: a}
3050
+ obj[foo[ bar ]]
3051
+
3052
+ // good
3053
+ obj[foo]
3054
+ obj['foo']
3055
+ const x = { [b]: a }
3056
+ obj[foo[bar]]
3057
+ ```
3058
+
3059
+ ---
3060
+
3061
+ <a name="whitespace--func-call-spacing"></a>
3062
+ [**19.16**](#whitespace--func-call-spacing) ‣ Avoid spaces between functions and their invocations.
3063
+
3064
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
3065
+
3066
+ <img src="../eslint.svg" height="18" align="center"/> [`func-call-spacing`](https://eslint.org/docs/rules/func-call-spacing)
3067
+
3068
+ ```typescript
3069
+ // bad
3070
+ func ();
3071
+
3072
+ func
3073
+ ();
3074
+
3075
+ // good
3076
+ func();
3077
+ ```
3078
+
3079
+ ---
3080
+
3081
+ <a name="whitespace--key-spacing"></a>
3082
+ [**19.17**](#whitespace--key-spacing) ‣ Enforce spacing between keys and values in object literal properties.
3083
+
3084
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
3085
+
3086
+ <img src="../eslint.svg" height="18" align="center"/> [`key-spacing`](https://eslint.org/docs/rules/key-spacing)
3087
+
3088
+ ```typescript
3089
+ // bad
3090
+ const obj = { foo : 42 };
3091
+ const obj2 = { foo:42 };
3092
+
3093
+ // good
3094
+ const obj = { foo: 42 };
3095
+ ```
3096
+
3097
+ ---
3098
+
3099
+ <a name="whitespace--no-trailing-spaces"></a>
3100
+ [**19.18**](#whitespace--no-trailing-spaces) ‣ Avoid trailing spaces at the end of lines.
3101
+
3102
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
3103
+
3104
+ <img src="../eslint.svg" height="18" align="center"/> [`no-trailing-spaces`](https://eslint.org/docs/rules/no-trailing-spaces)
3105
+
3106
+ ```typescript
3107
+ // bad
3108
+ const foo = 'bar';∙
3109
+
3110
+ // good
3111
+ const foo = 'bar';
3112
+ ```
3113
+
3114
+
3115
+ **[⬆ back to top](#table-of-contents)**
3116
+
3117
+ ## Commas
3118
+
3119
+ <a name="commas--leading-trailing"></a>
3120
+ [**20.1**](#commas--leading-trailing) ‣ Leading commas: **Nope.**
3121
+
3122
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
3123
+
3124
+ <img src="../eslint.svg" height="18" align="center"/> [`comma-style`](https://eslint.org/docs/rules/comma-style.html)
3125
+
3126
+ ```typescript
3127
+ // bad
3128
+ const story = [
3129
+ once
3130
+ , upon
3131
+ , aTime
3132
+ ];
3133
+
3134
+ // good
3135
+ const story = [
3136
+ once,
3137
+ upon,
3138
+ aTime,
3139
+ ];
3140
+
3141
+ // bad
3142
+ const hero = {
3143
+ firstName: 'Ada'
3144
+ , lastName: 'Lovelace'
3145
+ , birthYear: 1815
3146
+ , superPower: 'computers'
3147
+ };
3148
+
3149
+ // good
3150
+ const hero = {
3151
+ firstName: 'Ada',
3152
+ lastName: 'Lovelace',
3153
+ birthYear: 1815,
3154
+ superPower: 'computers',
3155
+ };
3156
+ ```
3157
+
3158
+ ---
3159
+
3160
+ <a name="commas--dangling"></a>
3161
+ [**20.2**](#commas--dangling) ‣ Additional trailing comma: **Yup.**
3162
+
3163
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
3164
+
3165
+ <img src="../eslint.svg" height="18" align="center"/> [`comma-dangle`](https://eslint.org/docs/rules/comma-dangle.html)
3166
+
3167
+ > Why? This leads to cleaner git diffs.
3168
+
3169
+ ```diff
3170
+ // bad - git diff without trailing comma
3171
+ const hero = {
3172
+ firstName: 'Florence',
3173
+ - lastName: 'Nightingale'
3174
+ + lastName: 'Nightingale',
3175
+ + inventorOf: ['coxcomb chart', 'modern nursing']
3176
+ };
3177
+
3178
+ // good - git diff with trailing comma
3179
+ const hero = {
3180
+ firstName: 'Florence',
3181
+ lastName: 'Nightingale',
3182
+ + inventorOf: ['coxcomb chart', 'modern nursing'],
3183
+ };
3184
+ ```
3185
+
3186
+ ```typescript
3187
+ // bad
3188
+ const hero = {
3189
+ firstName: 'Dana',
3190
+ lastName: 'Scully'
3191
+ };
3192
+
3193
+ const heroes = [
3194
+ 'Batman',
3195
+ 'Superman'
3196
+ ];
3197
+
3198
+ // good
3199
+ const hero = {
3200
+ firstName: 'Dana',
3201
+ lastName: 'Scully',
3202
+ };
3203
+
3204
+ const heroes = [
3205
+ 'Batman',
3206
+ 'Superman',
3207
+ ];
3208
+
3209
+ // bad
3210
+ function createHero(
3211
+ firstName: string,
3212
+ lastName: string,
3213
+ inventorOf: Invention
3214
+ ) {
3215
+ // does nothing
3216
+ }
3217
+
3218
+ // good
3219
+ function createHero(
3220
+ firstName: string,
3221
+ lastName: string,
3222
+ inventorOf: Invention,
3223
+ ) {
3224
+ // does nothing
3225
+ }
3226
+
3227
+ // good (note that a comma must not appear after a "rest" element)
3228
+ function createHero(
3229
+ firstName: string,
3230
+ lastName: string,
3231
+ inventorOf: Invention,
3232
+ ...heroArgs
3233
+ ) {
3234
+ // does nothing
3235
+ }
3236
+
3237
+ // bad
3238
+ createHero(
3239
+ firstName,
3240
+ lastName,
3241
+ inventorOf
3242
+ );
3243
+
3244
+ // good
3245
+ createHero(
3246
+ firstName,
3247
+ lastName,
3248
+ inventorOf,
3249
+ );
3250
+
3251
+ // good (note that a comma must not appear after a "rest" element)
3252
+ createHero(
3253
+ firstName,
3254
+ lastName,
3255
+ inventorOf,
3256
+ ...heroArgs
3257
+ );
3258
+ ```
3259
+
3260
+ **[⬆ back to top](#table-of-contents)**
3261
+
3262
+ ## Semicolons
3263
+
3264
+ <a name="semicolons--required"></a>
3265
+ [**21.1**](#semicolons--required) ‣ **Yup.**
3266
+
3267
+ <img src="../prettier.svg" height="18" align="center"/> **Enforced by Prettier**
3268
+
3269
+ <img src="../eslint.svg" height="18" align="center"/> [`semi`](https://eslint.org/docs/rules/semi.html)
3270
+
3271
+ > Why? When JavaScript encounters a line break without a semicolon, it uses a set of rules called [Automatic Semicolon Insertion](https://tc39.github.io/ecma262/#sec-automatic-semicolon-insertion) to determine whether it should regard that line break as the end of a statement, and (as the name implies) place a semicolon into your code before the line break if it thinks so. ASI contains a few eccentric behaviors, though, and your code will break if JavaScript misinterprets your line break. These rules will become more complicated as new features become a part of JavaScript. Explicitly terminating your statements and configuring your linter to catch missing semicolons will help prevent you from encountering issues.
3272
+
3273
+ ```typescript
3274
+ // bad - raises exception
3275
+ const luke = {}
3276
+ const leia = {}
3277
+ [luke, leia].forEach((jedi) => jedi.father = 'vader')
3278
+
3279
+ // bad - raises exception
3280
+ const reaction = "No! That’s impossible!"
3281
+ (async function meanwhileOnTheFalcon() {
3282
+ // handle `leia`, `lando`, `chewie`, `r2`, `c3p0`
3283
+ // ...
3284
+ }())
3285
+
3286
+ // bad - returns `undefined` instead of the value on the next line - always happens when `return` is on a line by itself because of ASI!
3287
+ function foo() {
3288
+ return
3289
+ 'search your feelings, you know it to be foo'
3290
+ }
3291
+
3292
+ // good
3293
+ const luke = {};
3294
+ const leia = {};
3295
+ [luke, leia].forEach((jedi) => {
3296
+ jedi.father = 'vader';
3297
+ });
3298
+
3299
+ // good
3300
+ const reaction = "No! That’s impossible!";
3301
+ (async function meanwhileOnTheFalcon() {
3302
+ // handle `leia`, `lando`, `chewie`, `r2`, `c3p0`
3303
+ // ...
3304
+ }());
3305
+
3306
+ // good
3307
+ function foo() {
3308
+ return 'search your feelings, you know it to be foo';
3309
+ }
3310
+ ```
3311
+
3312
+ [Read more](https://stackoverflow.com/questions/7365172/semicolon-before-self-invoking-function/7365214#7365214).
3313
+
3314
+ **[⬆ back to top](#table-of-contents)**
3315
+
3316
+ ## Type Casting & Coercion
3317
+
3318
+ <a name="coercion--explicit"></a>
3319
+ [**22.1**](#coercion--explicit) ‣ Perform type coercion at the beginning of the statement.
3320
+
3321
+ ---
3322
+
3323
+ <a name="coercion--strings"></a>
3324
+ [**22.2**](#coercion--strings) ‣ Strings:
3325
+
3326
+ <img src="../eslint.svg" height="18" align="center"/> [`no-new-wrappers`](https://eslint.org/docs/rules/no-new-wrappers)
3327
+
3328
+ ```typescript
3329
+ // => this.reviewScore = 9;
3330
+
3331
+ // bad
3332
+ const totalScore = new String(this.reviewScore); // typeof totalScore is "object" not "string"
3333
+
3334
+ // bad
3335
+ const totalScore = this.reviewScore + ''; // invokes this.reviewScore.valueOf()
3336
+
3337
+ // bad
3338
+ const totalScore = this.reviewScore.toString(); // isn’t guaranteed to return a string
3339
+
3340
+ // good
3341
+ const totalScore = String(this.reviewScore);
3342
+ ```
3343
+
3344
+ ---
3345
+
3346
+ <a name="coercion--numbers"></a>
3347
+ [**22.3**](#coercion--numbers) ‣ Numbers: Use `Number` for type casting and `parseInt` always with a radix for parsing strings.
3348
+
3349
+ <img src="../eslint.svg" height="18" align="center"/> [`radix`](https://eslint.org/docs/rules/radix), [`no-new-wrappers`](https://eslint.org/docs/rules/no-new-wrappers)
3350
+
3351
+ > Why? The `parseInt` function produces an integer value dictated by interpretation of the contents of the string argument according to the specified radix. Leading whitespace in string is ignored. If radix is `undefined` or `0`, it is assumed to be `10` except when the number begins with the character pairs `0x` or `0X`, in which case a radix of 16 is assumed. This differs from ECMAScript 3, which merely discouraged (but allowed) octal interpretation. Many implementations have not adopted this behavior as of 2013. And, because older browsers must be supported, always specify a radix.
3352
+
3353
+ ```typescript
3354
+ const inputValue = '4';
3355
+
3356
+ // bad
3357
+ const val = new Number(inputValue);
3358
+
3359
+ // bad
3360
+ const val = +inputValue;
3361
+
3362
+ // bad
3363
+ const val = inputValue >> 0;
3364
+
3365
+ // bad
3366
+ const val = parseInt(inputValue);
3367
+
3368
+ // good
3369
+ const val = Number(inputValue);
3370
+
3371
+ // good
3372
+ const val = parseInt(inputValue, 10);
3373
+ ```
3374
+
3375
+ ---
3376
+
3377
+ <a name="coercion--comment-deviations"></a>
3378
+ [**22.4**](#coercion--comment-deviations) ‣ If for whatever reason you are doing something wild and `parseInt` is your bottleneck and need to use Bitshift for [performance reasons](https://jsperf.com/coercion-vs-casting/3), leave a comment explaining why and what you’re doing.
3379
+
3380
+ ```typescript
3381
+ // good
3382
+ /**
3383
+ * parseInt was the reason my code was slow.
3384
+ * Bitshifting the String to coerce it to a
3385
+ * Number made it a lot faster.
3386
+ */
3387
+ const val = inputValue >> 0;
3388
+ ```
3389
+
3390
+ ---
3391
+
3392
+ <a name="coercion--bitwise"></a>
3393
+ [**22.5**](#coercion--bitwise) ‣ **Note:** Be careful when using bitshift operations. Numbers are represented as [64-bit values](https://es5.github.io/#x4.3.19), but bitshift operations always return a 32-bit integer ([source](https://es5.github.io/#x11.7)). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. [Discussion](https://github.com/airbnb/javascript/issues/109). Largest signed 32-bit Int is 2,147,483,647:
3394
+
3395
+ ```typescript
3396
+ 2147483647 >> 0; // => 2147483647
3397
+ 2147483648 >> 0; // => -2147483648
3398
+ 2147483649 >> 0; // => -2147483647
3399
+ ```
3400
+
3401
+ ---
3402
+
3403
+ <a name="coercion--booleans"></a>
3404
+ [**22.6**](#coercion--booleans) ‣ Booleans:
3405
+
3406
+ <img src="../eslint.svg" height="18" align="center"/> [`no-new-wrappers`](https://eslint.org/docs/rules/no-new-wrappers)
3407
+
3408
+ ```typescript
3409
+ const age = 0;
3410
+
3411
+ // bad
3412
+ const hasAge = new Boolean(age);
3413
+
3414
+ // good
3415
+ const hasAge = Boolean(age);
3416
+
3417
+ // best
3418
+ const hasAge = !!age;
3419
+ ```
3420
+
3421
+ **[⬆ back to top](#table-of-contents)**
3422
+
3423
+ ## Naming Conventions
3424
+
3425
+ <a name="naming--descriptive"></a>
3426
+ [**23.1**](#naming--descriptive) ‣ Avoid single letter names. Be descriptive with your naming.
3427
+
3428
+ <img src="../eslint.svg" height="18" align="center"/> [`id-length`](https://eslint.org/docs/rules/id-length)
3429
+
3430
+ ```typescript
3431
+ // bad
3432
+ function q() {
3433
+ // ...
3434
+ }
3435
+
3436
+ // good
3437
+ function query() {
3438
+ // ...
3439
+ }
3440
+ ```
3441
+
3442
+ ---
3443
+
3444
+ <a name="naming--camelCase"></a>
3445
+ [**23.2**](#naming--camelCase) ‣ Use camelCase when naming objects, functions, and instances.
3446
+
3447
+ <img src="../eslint.svg" height="18" align="center"/> [`camelcase`](https://eslint.org/docs/rules/camelcase.html)
3448
+
3449
+ ```typescript
3450
+ // bad
3451
+ const OBJEcttsssss = {};
3452
+ const this_is_my_object = {};
3453
+ function c() {}
3454
+
3455
+ // good
3456
+ const thisIsMyObject = {};
3457
+ function thisIsMyFunction() {}
3458
+ ```
3459
+
3460
+ ---
3461
+
3462
+ <a name="naming--PascalCase"></a>
3463
+ [**23.3**](#naming--PascalCase) ‣ Use PascalCase only when naming constructors or classes.
3464
+
3465
+ <img src="../eslint.svg" height="18" align="center"/> [`new-cap`](https://eslint.org/docs/rules/new-cap.html)
3466
+
3467
+ ```typescript
3468
+ // bad
3469
+ function user(options) {
3470
+ this.name = options.name;
3471
+ }
3472
+
3473
+ const bad = new user({
3474
+ name: 'nope',
3475
+ });
3476
+
3477
+ // good
3478
+ class User {
3479
+ constructor(options) {
3480
+ this.name = options.name;
3481
+ }
3482
+ }
3483
+
3484
+ const good = new User({
3485
+ name: 'yup',
3486
+ });
3487
+ ```
3488
+
3489
+ ---
3490
+
3491
+ <a name="naming--leading-underscore"></a>
3492
+ [**23.4**](#naming--leading-underscore) ‣ Do not use trailing or leading underscores.
3493
+
3494
+ <img src="../eslint.svg" height="18" align="center"/> [`no-underscore-dangle`](https://eslint.org/docs/rules/no-underscore-dangle.html)
3495
+
3496
+ > Why? Although a leading underscore has long been a common convention to mean “private”, in fact, these properties are fully public, and as such, are part of your public API contract. This convention might lead developers to wrongly think that a change won’t count as breaking, or that tests aren’t needed. tl;dr: if you want something to be “private”, it must not be observably present. With the addition of private class fields in ES2022, there is a genuine way to do this, so the informal convention is obsolete.
3497
+
3498
+ ```typescript
3499
+ // bad
3500
+ this.__firstName__ = 'Panda';
3501
+ this.firstName_ = 'Panda';
3502
+ this._firstName = 'Panda';
3503
+
3504
+ // good
3505
+ this.firstName = 'Panda';
3506
+
3507
+ // good, in environments where WeakMaps are available
3508
+ // see https://kangax.github.io/compat-table/es6/#test-WeakMap
3509
+ const firstNames = new WeakMap();
3510
+ firstNames.set(this, 'Panda');
3511
+ ```
3512
+
3513
+ ---
3514
+
3515
+ <a name="naming--self-this"></a>
3516
+ [**23.5**](#naming--self-this) ‣ Don’t save references to `this`. Use arrow functions or [Function#bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).
3517
+
3518
+ ```typescript
3519
+ // bad
3520
+ function foo() {
3521
+ const self = this;
3522
+ return function () {
3523
+ console.log(self);
3524
+ };
3525
+ }
3526
+
3527
+ // bad
3528
+ function foo() {
3529
+ const that = this;
3530
+ return function () {
3531
+ console.log(that);
3532
+ };
3533
+ }
3534
+
3535
+ // good
3536
+ function foo() {
3537
+ return () => {
3538
+ console.log(this);
3539
+ };
3540
+ }
3541
+ ```
3542
+
3543
+ ---
3544
+
3545
+ <a name="naming--filename-matches-export"></a>
3546
+ [**23.6**](#naming--filename-matches-export) ‣ A base filename should exactly match the name of its default export.
3547
+
3548
+ ```typescript
3549
+ // file 1 contents
3550
+ class CheckBox {
3551
+ // ...
3552
+ }
3553
+ export default CheckBox;
3554
+
3555
+ // file 2 contents
3556
+ export default function fortyTwo() { return 42; }
3557
+
3558
+ // file 3 contents
3559
+ export default function insideDirectory() {}
3560
+
3561
+ // in some other file
3562
+ // bad
3563
+ import CheckBox from './checkBox'; // PascalCase import/export, camelCase filename
3564
+ import FortyTwo from './FortyTwo'; // PascalCase import/filename, camelCase export
3565
+ import InsideDirectory from './InsideDirectory'; // PascalCase import/filename, camelCase export
3566
+
3567
+ // bad
3568
+ import CheckBox from './check_box'; // PascalCase import/export, snake_case filename
3569
+ import forty_two from './forty_two'; // snake_case import/filename, camelCase export
3570
+ import inside_directory from './inside_directory'; // snake_case import, camelCase export
3571
+ import index from './inside_directory/index'; // requiring the index file explicitly
3572
+ import insideDirectory from './insideDirectory/index'; // requiring the index file explicitly
3573
+
3574
+ // good
3575
+ import CheckBox from './CheckBox'; // PascalCase export/import/filename
3576
+ import fortyTwo from './fortyTwo'; // camelCase export/import/filename
3577
+ import insideDirectory from './insideDirectory'; // camelCase export/import/directory name/implicit "index"
3578
+ // ^ supports both insideDirectory.js and insideDirectory/index.js
3579
+ ```
3580
+
3581
+ ---
3582
+
3583
+ <a name="naming--PascalCase-singleton"></a>
3584
+ [**23.7**](#naming--PascalCase-singleton) ‣ Use PascalCase when you export a constructor / class / singleton / function library / bare object.
3585
+
3586
+ ```typescript
3587
+ const AirbnbStyleGuide = {
3588
+ es6: {
3589
+ },
3590
+ };
3591
+
3592
+ export default AirbnbStyleGuide;
3593
+ ```
3594
+
3595
+ ---
3596
+
3597
+ <a name="naming--Acronyms-and-Initialisms"></a>
3598
+ [**23.8**](#naming--Acronyms-and-Initialisms) ‣ Acronyms and initialisms should always be all uppercased, or all lowercased.
3599
+
3600
+ > Why? Names are for readability, not to appease a computer algorithm.
3601
+
3602
+ ```typescript
3603
+ // bad
3604
+ import SmsContainer from './containers/SmsContainer';
3605
+
3606
+ // bad
3607
+ const HttpRequests = [
3608
+ // ...
3609
+ ];
3610
+
3611
+ // good
3612
+ import SMSContainer from './containers/SMSContainer';
3613
+
3614
+ // good
3615
+ const HTTPRequests = [
3616
+ // ...
3617
+ ];
3618
+
3619
+ // also good
3620
+ const httpRequests = [
3621
+ // ...
3622
+ ];
3623
+
3624
+ // best
3625
+ import TextMessageContainer from './containers/TextMessageContainer';
3626
+
3627
+ // best
3628
+ const requests = [
3629
+ // ...
3630
+ ];
3631
+ ```
3632
+
3633
+ ---
3634
+
3635
+ <a name="naming--uppercase"></a>
3636
+ [**23.9**](#naming--uppercase) ‣ You may optionally uppercase a constant only if it (1) is exported, (2) is a `const` (it can not be reassigned), and (3) the programmer can trust it (and its nested properties) to never change.
3637
+
3638
+ > Why? This is an additional tool to assist in situations where the programmer would be unsure if a variable might ever change. UPPERCASE_VARIABLES are letting the programmer know that they can trust the variable (and its properties) not to change.
3639
+ - What about all `const` variables? - This is unnecessary, so uppercasing should not be used for constants within a file. It should be used for exported constants however.
3640
+ - What about exported objects? - Uppercase at the top level of export (e.g. `EXPORTED_OBJECT.key`) and maintain that all nested properties do not change.
3641
+
3642
+ ```typescript
3643
+ // bad
3644
+ const PRIVATE_VARIABLE = 'should not be unnecessarily uppercased within a file';
3645
+
3646
+ // bad
3647
+ export const THING_TO_BE_CHANGED = 'should obviously not be uppercased';
3648
+
3649
+ // bad
3650
+ export let REASSIGNABLE_VARIABLE = 'do not use let with uppercase variables';
3651
+
3652
+ // ---
3653
+
3654
+ // allowed but does not supply semantic value
3655
+ export const apiKey = 'SOMEKEY';
3656
+
3657
+ // better in most cases
3658
+ export const API_KEY = 'SOMEKEY';
3659
+
3660
+ // ---
3661
+
3662
+ // bad - unnecessarily uppercases key while adding no semantic value
3663
+ export const MAPPING = {
3664
+ KEY: 'value'
3665
+ };
3666
+
3667
+ // good
3668
+ export const MAPPING = {
3669
+ key: 'value'
3670
+ };
3671
+ ```
3672
+
3673
+ **[⬆ back to top](#table-of-contents)**
3674
+
3675
+ ## Accessors
3676
+
3677
+ <a name="accessors--not-required"></a>
3678
+ [**24.1**](#accessors--not-required) ‣ Accessor functions for properties are not required.
3679
+
3680
+ ---
3681
+
3682
+ <a name="accessors--no-getters-setters"></a>
3683
+ [**24.2**](#accessors--no-getters-setters) ‣ Do not use JavaScript getters/setters as they cause unexpected side effects and are harder to test, maintain, and reason about. Instead, if you do make accessor functions, use `getVal()` and `setVal('hello')`.
3684
+
3685
+ ```typescript
3686
+ // bad
3687
+ class Dragon {
3688
+ get age(): number {
3689
+ // ...
3690
+ }
3691
+
3692
+ set age(value: number) {
3693
+ // ...
3694
+ }
3695
+ }
3696
+
3697
+ // good
3698
+ class Dragon {
3699
+ getAge(): number {
3700
+ // ...
3701
+ }
3702
+
3703
+ setAge(value: number) {
3704
+ // ...
3705
+ }
3706
+ }
3707
+ ```
3708
+
3709
+ ---
3710
+
3711
+ <a name="accessors--boolean-prefix"></a>
3712
+ [**24.3**](#accessors--boolean-prefix) ‣ If the property/method is a `boolean`, use `isVal()` or `hasVal()`.
3713
+
3714
+ ```typescript
3715
+ // bad
3716
+ if (!dragon.age()) {
3717
+ return false;
3718
+ }
3719
+
3720
+ // good
3721
+ if (!dragon.hasAge()) {
3722
+ return false;
3723
+ }
3724
+ ```
3725
+
3726
+ ---
3727
+
3728
+ <a name="accessors--consistent"></a>
3729
+ [**24.4**](#accessors--consistent) ‣ It’s okay in rare cases to create `get()` and `set()` functions, but be consistent.
3730
+
3731
+ ```typescript
3732
+ class Jedi {
3733
+ constructor(options: IJediOptions = {}) {
3734
+ const lightsaber = options.lightsaber || 'blue';
3735
+ this.set('lightsaber', lightsaber);
3736
+ }
3737
+
3738
+ set(key: string, val: any) {
3739
+ this[key] = val;
3740
+ }
3741
+
3742
+ get<T>(key: string): T {
3743
+ return this[key];
3744
+ }
3745
+ }
3746
+ ```
3747
+
3748
+ **[⬆ back to top](#table-of-contents)**
3749
+
3750
+ ## Events
3751
+
3752
+ <a name="events--hash"></a>
3753
+ [**25.1**](#events--hash) ‣ When attaching data payloads to events, pass an object literal instead of a raw value. This allows a subsequent contributor to add more data to the event payload without finding and updating every handler for the event. For example, instead of:
3754
+
3755
+ ```typescript
3756
+ // bad
3757
+ const event = new CustomEvent('listingUpdated', { detail: listing.id });
3758
+
3759
+ someElement.addEventListener('listingUpdated', (event: CustomEvent<string>) => {
3760
+ // do something with event.detail
3761
+ });
3762
+
3763
+ someElement.dispatchEvent(event);
3764
+ ```
3765
+
3766
+ prefer:
3767
+
3768
+ ```typescript
3769
+ // good
3770
+ interface ListingUpdatedEventDetail {
3771
+ listingId: string;
3772
+ }
3773
+ const event = new CustomEvent<ListingUpdatedEventDetail>(
3774
+ 'listingUpdated',
3775
+ {
3776
+ detail: {
3777
+ listingId: listing.id,
3778
+ },
3779
+ },
3780
+ );
3781
+
3782
+ someElement.addEventListener(
3783
+ 'listingUpdated',
3784
+ (event: CustomEvent<ListingUpdatedEventDetail>) => {
3785
+ // do something with event.detail.listingId
3786
+ },
3787
+ );
3788
+
3789
+ someElement.dispatchEvent(event);
3790
+ ```
3791
+
3792
+ **[⬆ back to top](#table-of-contents)**
3793
+
3794
+ ## Standard Library
3795
+
3796
+ The [Standard Library](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects)
3797
+ contains utilities that are functionally broken but remain for legacy reasons.
3798
+
3799
+ <a name="standard-library--isnan"></a>
3800
+ [**26.1**](#standard-library--isnan) ‣ Use `Number.isNaN` instead of global `isNaN`.
3801
+
3802
+
3803
+ <img src="../eslint.svg" height="18" align="center"/> [`no-restricted-globals`](https://eslint.org/docs/rules/no-restricted-globals)
3804
+
3805
+ > Why? The global `isNaN` coerces non-numbers to numbers, returning true for anything that coerces to NaN.
3806
+ > If this behavior is desired, make it explicit.
3807
+
3808
+ ```typescript
3809
+ // bad
3810
+ isNaN('1.2'); // false
3811
+ isNaN('1.2.3'); // true
3812
+
3813
+ // good
3814
+ Number.isNaN('1.2.3'); // false
3815
+ Number.isNaN(Number('1.2.3')); // true
3816
+ ```
3817
+
3818
+ ---
3819
+
3820
+ <a name="standard-library--isfinite"></a>
3821
+ [**26.2**](#standard-library--isfinite) ‣ Use `Number.isFinite` instead of global `isFinite`.
3822
+
3823
+ <img src="../eslint.svg" height="18" align="center"/> [`no-restricted-globals`](https://eslint.org/docs/rules/no-restricted-globals)
3824
+
3825
+ > Why? The global `isFinite` coerces non-numbers to numbers, returning true for anything that coerces to a finite number.
3826
+ > If this behavior is desired, make it explicit.
3827
+
3828
+ ```typescript
3829
+ // bad
3830
+ isFinite('2e3'); // true
3831
+
3832
+ // good
3833
+ Number.isFinite('2e3'); // false
3834
+ Number.isFinite(parseInt('2e3', 10)); // true
3835
+ ```
3836
+
3837
+ **[⬆ back to top](#table-of-contents)**
3838
+
3839
+ ## Language Proposals
3840
+
3841
+ <a name="tc39-proposals"></a>
3842
+ [**27.1**](#tc39-proposals) ‣ Do not use [TC39 proposals](https://github.com/tc39/proposals) that have not reached stage 3.
3843
+
3844
+ > Why? [They are not finalized](https://tc39.github.io/process-document/), and they are subject to change or to be withdrawn entirely. We want to use JavaScript, and proposals are not JavaScript yet.
3845
+
3846
+ **[⬆ back to top](#table-of-contents)**
3847
+
3848
+ ## Testing
3849
+
3850
+ <a name="testing--yup"></a>
3851
+ [**28.1**](#testing--yup) ‣ **Yup.**
3852
+
3853
+ ```typescript
3854
+ function foo() {
3855
+ return true;
3856
+ }
3857
+ ```
3858
+
3859
+ ---
3860
+
3861
+ <a name="testing--for-real"></a>
3862
+ [**28.2**](#testing--for-real) ‣ **No, but seriously**:
3863
+ - Refer to the [Web UI Frameworks & Tools guardrail](https://atlassian.spscommerce.com/wiki/pages/viewpage.action?spaceKey=Guardrails&title=Web+UI+Frameworks+and+Tools) for guidance on what testing tools we use and what kinds of testing you should be doing.
3864
+ - Strive to write many small pure functions, and minimize where mutations occur.
3865
+ - Be cautious about stubs and mocks - they can make your tests more brittle.
3866
+ - 100% test coverage is a good goal to strive for, even if it’s not always practical to reach it. Don't write crappy tests just to bump the number.
3867
+ - Whenever you fix a bug, _write a regression test_. A bug fixed without a regression test is almost certainly going to break again in the future.
3868
+
3869
+ **[⬆ back to top](#table-of-contents)**
3870
+
3871
+ ## Resources
3872
+
3873
+ **TODO:** Create list of resources we recommend - blog posts, books, YouTube videos, etc
3874
+
3875
+ **[⬆ back to top](#table-of-contents)**
3876
+
3877
+ # };