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