pi-usereq 0.37.0 → 0.38.0

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.
@@ -0,0 +1,2954 @@
1
+ # Google TypeScript Style Guide
2
+
3
+ This guide is based on the internal Google TypeScript style guide, but it has been slightly adjusted to remove Google-internal sections. Google's internal environment has different constraints on TypeScript than you might find outside of Google. The advice here is specifically useful for people authoring code they intend to import into Google, but otherwise may not apply in your external environment.
4
+
5
+ There is no automatic deployment process for this version as it's pushed on-demand by volunteers.
6
+
7
+ ## Introduction
8
+
9
+ ### Terminology notes
10
+
11
+ This Style Guide uses [RFC 2119](https://tools.ietf.org/html/rfc2119) terminology when using the phrases *must* , *must not* , *should* , *should not* , and *may* . The terms *prefer* and *avoid* correspond to *should* and *should not* , respectively. Imperative and declarative statements are prescriptive and correspond to *must* .
12
+
13
+ ### Guide notes
14
+
15
+ All examples given are **non-normative** and serve only to illustrate the normative language of the style guide. That is, while the examples are in Google Style, they may not illustrate the *only* stylish way to represent the code. Optional formatting choices made in examples must not be enforced as rules.
16
+
17
+ ## Source file basics
18
+
19
+ ### File encoding: UTF-8
20
+
21
+ Source files are encoded in **UTF-8** .
22
+
23
+ #### Whitespace characters
24
+
25
+ Aside from the line terminator sequence, the ASCII horizontal space character (0x20) is the only whitespace character that appears anywhere in a source file. This implies that all other whitespace characters in string literals are escaped.
26
+
27
+ #### Special escape sequences
28
+
29
+ For any character that has a special escape sequence ( `\'` , `\"` , `\\` , `\b` , `\f` , `\n` , `\r` , `\t` , `\v` ), that sequence is used rather than the corresponding numeric escape (e.g `\x0a` , `\u000a` , or `\u{a}` ). Legacy octal escapes are never used.
30
+
31
+ #### Non-ASCII characters
32
+
33
+ For the remaining non-ASCII characters, use the actual Unicode character (e.g. `∞` ). For non-printable characters, the equivalent hex or Unicode escapes (e.g. `\u221e` ) can be used along with an explanatory comment.
34
+
35
+ ```
36
+ // Perfectly clear, even without a comment.
37
+ const units = 'μs';
38
+
39
+ // Use escapes for non-printable characters.
40
+ const output = '\ufeff' + content; // byte order mark
41
+ ```
42
+
43
+ ```
44
+ // Hard to read and prone to mistakes, even with the comment.
45
+ const units = '\u03bcs'; // Greek letter mu, 's'
46
+
47
+ // The reader has no idea what this is.
48
+ const output = '\ufeff' + content;
49
+ ```
50
+
51
+ ## Source file structure
52
+
53
+ Files consist of the following, **in order** :
54
+
55
+ 1. Copyright information, if present
56
+ 2. JSDoc with `@fileoverview` , if present
57
+ 3. Imports, if present
58
+ 4. The file's implementation
59
+
60
+ **Exactly one blank line** separates each section that is present.
61
+
62
+ ### Copyright information
63
+
64
+ If license or copyright information is necessary in a file, add it in a JSDoc at the top of the file.
65
+
66
+ ### @fileoverview JSDoc
67
+
68
+ A file may have a top-level `@fileoverview` JSDoc. If present, it may provide a description of the file's content, its uses, or information about its dependencies. Wrapped lines are not indented.
69
+
70
+ Example:
71
+
72
+ ```
73
+ /**
74
+ * @fileoverview Description of file. Lorem ipsum dolor sit amet, consectetur
75
+ * adipiscing elit, sed do eiusmod tempor incididunt.
76
+ */
77
+ ```
78
+
79
+ ### Imports
80
+
81
+ There are four variants of import statements in ES6 and TypeScript:
82
+
83
+ | Import type | Example | Use for |
84
+ |-------------------------------|----------------------------------|-----------------------------------------------------------------------------------|
85
+ | module[ module\_import] | `import * as foo from '...';` | TypeScript imports |
86
+ | named[ destructuring\_import] | `import {SomeThing} from '...';` | TypeScript imports |
87
+ | default | `import SomeThing from '...';` | Only for other external code that requires them |
88
+ | side-effect | `import '...';` | Only to import libraries for their side-effects on load (such as custom elements) |
89
+
90
+ ```
91
+ // Good: choose between two options as appropriate (see below).
92
+ import * as ng from '@angular/core';
93
+ import {Foo} from './foo';
94
+
95
+ // Only when needed: default imports.
96
+ import Button from 'Button';
97
+
98
+ // Sometimes needed to import libraries for their side effects:
99
+ import 'jasmine';
100
+ import '@polymer/paper-button';
101
+ ```
102
+
103
+ #### Import paths
104
+
105
+ TypeScript code *must* use paths to import other TypeScript code. Paths *may* be relative, i.e. starting with `.` or `..` , or rooted at the base directory, e.g. `root/path/to/file` .
106
+
107
+ Code *should* use relative imports ( `./foo` ) rather than absolute imports `path/to/foo` when referring to files within the same (logical) project as this allows to move the project around without introducing changes in these imports.
108
+
109
+ Consider limiting the number of parent steps ( `../../../` ) as those can make module and path structures hard to understand.
110
+
111
+ ```
112
+ import {Symbol1} from 'path/from/root';
113
+ import {Symbol2} from '../parent/file';
114
+ import {Symbol3} from './sibling';
115
+ ```
116
+
117
+ #### Namespace versus named imports
118
+
119
+ Both namespace and named imports can be used.
120
+
121
+ Prefer named imports for symbols used frequently in a file or for symbols that have clear names, for example Jasmine's `describe` and `it` . Named imports can be aliased to clearer names as needed with `as` .
122
+
123
+ Prefer namespace imports when using many different symbols from large APIs. A namespace import, despite using the `*` character, is not comparable to a wildcard import as seen in other languages. Instead, namespace imports give a name to all the exports of a module, and each exported symbol from the module becomes a property on the module name. Namespace imports can aid readability for exported symbols that have common names like `Model` or `Controller` without the need to declare aliases.
124
+
125
+ ```
126
+ // Bad: overlong import statement of needlessly namespaced names.
127
+ import {Item as TableviewItem, Header as TableviewHeader, Row as TableviewRow,
128
+ Model as TableviewModel, Renderer as TableviewRenderer} from './tableview';
129
+
130
+ let item: TableviewItem|undefined;
131
+ ```
132
+
133
+ ```
134
+ // Better: use the module for namespacing.
135
+ import * as tableview from './tableview';
136
+
137
+ let item: tableview.Item|undefined;
138
+ ```
139
+
140
+ ```
141
+ import * as testing from './testing';
142
+
143
+ // Bad: The module name does not improve readability.
144
+ testing.describe('foo', () => {
145
+ testing.it('bar', () => {
146
+ testing.expect(null).toBeNull();
147
+ testing.expect(undefined).toBeUndefined();
148
+ });
149
+ });
150
+ ```
151
+
152
+ ```
153
+ // Better: give local names for these common functions.
154
+ import {describe, it, expect} from './testing';
155
+
156
+ describe('foo', () => {
157
+ it('bar', () => {
158
+ expect(null).toBeNull();
159
+ expect(undefined).toBeUndefined();
160
+ });
161
+ });
162
+ ```
163
+
164
+ ##### Special case: Apps JSPB protos
165
+
166
+ Apps JSPB protos must use named imports, even when it leads to long import lines.
167
+
168
+ This rule exists to aid in build performance and dead code elimination since often `.proto` files contain many `message` s that are not all needed together. By leveraging destructured imports the build system can create finer grained dependencies on Apps JSPB messages while preserving the ergonomics of path based imports.
169
+
170
+ ```
171
+ // Good: import the exact set of symbols you need from the proto file.
172
+ import {Foo, Bar} from './foo.proto';
173
+
174
+ function copyFooBar(foo: Foo, bar: Bar) {...}
175
+ ```
176
+
177
+ #### Renaming imports
178
+
179
+ Code *should* fix name collisions by using a namespace import or renaming the exports themselves. Code *may* rename imports ( `import {SomeThing as SomeOtherThing}` ) if needed.
180
+
181
+ Three examples where renaming can be helpful:
182
+
183
+ 1. If it's necessary to avoid collisions with other imported symbols.
184
+ 2. If the imported symbol name is generated.
185
+ 3. If importing symbols whose names are unclear by themselves, renaming can improve code clarity. For example, when using RxJS the `from` function might be more readable when renamed to `observableFrom` .
186
+
187
+ ### Exports
188
+
189
+ Use named exports in all code:
190
+
191
+ ```
192
+ // Use named exports:
193
+ export class Foo { ... }
194
+ ```
195
+
196
+ Do not use default exports. This ensures that all imports follow a uniform pattern.
197
+
198
+ ```
199
+ // Do not use default exports:
200
+ export default class Foo { ... } // BAD!
201
+ ```
202
+
203
+ Why?
204
+
205
+ Default exports provide no canonical name, which makes central maintenance difficult with relatively little benefit to code owners, including potentially decreased readability:
206
+
207
+ ```
208
+ import Foo from './bar'; // Legal.
209
+ import Bar from './bar'; // Also legal.
210
+ ```
211
+
212
+ Named exports have the benefit of erroring when import statements try to import something that hasn't been declared. In `foo.ts` :
213
+
214
+ ```
215
+ const foo = 'blah';
216
+ export default foo;
217
+ ```
218
+
219
+ And in `bar.ts` :
220
+
221
+ ```
222
+ import {fizz} from './foo';
223
+ ```
224
+
225
+ Results in `error TS2614: Module '"./foo"' has no exported member 'fizz'.` While `bar.ts` :
226
+
227
+ ```
228
+ import fizz from './foo';
229
+ ```
230
+
231
+ Results in `fizz === foo` , which is probably unexpected and difficult to debug.
232
+
233
+ Additionally, default exports encourage people to put everything into one big object to namespace it all together:
234
+
235
+ ```
236
+ export default class Foo {
237
+ static SOME_CONSTANT = ...
238
+ static someHelpfulFunction() { ... }
239
+ ...
240
+ }
241
+ ```
242
+
243
+ With the above pattern, we have file scope, which can be used as a namespace. We also have a perhaps needless second scope (the class `Foo` ) that can be ambiguously used as both a type and a value in other files.
244
+
245
+ Instead, prefer use of file scope for namespacing, as well as named exports:
246
+
247
+ ```
248
+ export const SOME_CONSTANT = ...
249
+ export function someHelpfulFunction()
250
+ export class Foo {
251
+ // only class stuff here
252
+ }
253
+ ```
254
+
255
+ #### Export visibility
256
+
257
+ TypeScript does not support restricting the visibility for exported symbols. Only export symbols that are used outside of the module. Generally minimize the exported API surface of modules.
258
+
259
+ #### Mutable exports
260
+
261
+ Regardless of technical support, mutable exports can create hard to understand and debug code, in particular with re-exports across multiple modules. One way to paraphrase this style point is that `export let` is not allowed.
262
+
263
+ ```
264
+ export let foo = 3;
265
+ // In pure ES6, foo is mutable and importers will observe the value change after a second.
266
+ // In TS, if foo is re-exported by a second file, importers will not see the value change.
267
+ window.setTimeout(() => {
268
+ foo = 4;
269
+ }, 1000 /* ms */);
270
+ ```
271
+
272
+ If one needs to support externally accessible and mutable bindings, they *should* instead use explicit getter functions.
273
+
274
+ ```
275
+ let foo = 3;
276
+ window.setTimeout(() => {
277
+ foo = 4;
278
+ }, 1000 /* ms */);
279
+ // Use an explicit getter to access the mutable export.
280
+ export function getFoo() { return foo; };
281
+ ```
282
+
283
+ For the common pattern of conditionally exporting either of two values, first do the conditional check, then the export. Make sure that all exports are final after the module's body has executed.
284
+
285
+ ```
286
+ function pickApi() {
287
+ if (useOtherApi()) return OtherApi;
288
+ return RegularApi;
289
+ }
290
+ export const SomeApi = pickApi();
291
+ ```
292
+
293
+ #### Container classes
294
+
295
+ Do not create container classes with static methods or properties for the sake of namespacing.
296
+
297
+ ```
298
+ export class Container {
299
+ static FOO = 1;
300
+ static bar() { return 1; }
301
+ }
302
+ ```
303
+
304
+ Instead, export individual constants and functions:
305
+
306
+ ```
307
+ export const FOO = 1;
308
+ export function bar() { return 1; }
309
+ ```
310
+
311
+ ### Import and export type
312
+
313
+ #### Import type
314
+
315
+ You may use `import type {...}` when you use the imported symbol only as a type. Use regular imports for values:
316
+
317
+ ```
318
+ import type {Foo} from './foo';
319
+ import {Bar} from './foo';
320
+
321
+ import {type Foo, Bar} from './foo';
322
+ ```
323
+
324
+ Why?
325
+
326
+ The TypeScript compiler automatically handles the distinction and does not insert runtime loads for type references. So why annotate type imports?
327
+
328
+ The TypeScript compiler can run in 2 modes:
329
+
330
+ - In development mode, we typically want quick iteration loops. The compiler transpiles to JavaScript without full type information. This is much faster, but requires `import type` in certain cases.
331
+ - In production mode, we want correctness. The compiler type checks everything and ensures `import type` is used correctly.
332
+
333
+ Note: If you need to force a runtime load for side effects, use `import '...';` . See
334
+
335
+ #### Export type
336
+
337
+ Use `export type` when re-exporting a type, e.g.:
338
+
339
+ ```
340
+ export type {AnInterface} from './foo';
341
+ ```
342
+
343
+ Why?
344
+
345
+ `export type` is useful to allow type re-exports in file-by-file transpilation. See [`isolatedModules`](https://www.typescriptlang.org/tsconfig#exports-of-non-value-identifiers) [docs](https://www.typescriptlang.org/tsconfig#exports-of-non-value-identifiers) .
346
+
347
+ `export type` might also seem useful to avoid ever exporting a value symbol for an API. However it does not give guarantees, either: downstream code might still import an API through a different path. A better way to split & guarantee type vs value usages of an API is to actually split the symbols into e.g. `UserService` and `AjaxUserService` . This is less error prone and also better communicates intent.
348
+
349
+ #### Use modules not namespaces
350
+
351
+ TypeScript supports two methods to organize code: *namespaces* and *modules* , but namespaces are disallowed. That is, your code *must* refer to code in other files using imports and exports of the form `import {foo} from 'bar';`
352
+
353
+ Your code *must not* use the `namespace Foo { ... }` construct. `namespace` s *may* only be used when required to interface with external, third party code. To semantically namespace your code, use separate files.
354
+
355
+ Code *must not* use `require` (as in `import x = require('...');` ) for imports. Use ES6 module syntax.
356
+
357
+ ```
358
+ // Bad: do not use namespaces:
359
+ namespace Rocket {
360
+ function launch() { ... }
361
+ }
362
+
363
+ // Bad: do not use <reference>
364
+ /// <reference path="..."/>
365
+
366
+ // Bad: do not use require()
367
+ import x = require('mydep');
368
+ ```
369
+
370
+ NB: TypeScript `namespace` s used to be called internal modules and used to use the `module` keyword in the form `module Foo { ... }` . Don't use that either. Always use ES6 imports.
371
+
372
+ ## Language features
373
+
374
+ This section delineates which features may or may not be used, and any additional constraints on their use.
375
+
376
+ Language features which are not discussed in this style guide *may* be used with no recommendations of their usage.
377
+
378
+ ### Local variable declarations
379
+
380
+ #### Use const and let
381
+
382
+ Always use `const` or `let` to declare variables. Use `const` by default, unless a variable needs to be reassigned. Never use `var` .
383
+
384
+ ```
385
+ const foo = otherValue; // Use if "foo" never changes.
386
+ let bar = someValue; // Use if "bar" is ever assigned into later on.
387
+ ```
388
+
389
+ `const` and `let` are block scoped, like variables in most other languages. `var` in JavaScript is function scoped, which can cause difficult to understand bugs. Don't use it.
390
+
391
+ ```
392
+ var foo = someValue; // Don't use - var scoping is complex and causes bugs.
393
+ ```
394
+
395
+ Variables *must not* be used before their declaration.
396
+
397
+ #### One variable per declaration
398
+
399
+ Every local variable declaration declares only one variable: declarations such as `let a = 1, b = 2;` are not used.
400
+
401
+ ### Array literals
402
+
403
+ #### Do not use the Array constructor
404
+
405
+ *Do not* use the `Array()` constructor, with or without `new` . It has confusing and contradictory usage:
406
+
407
+ ```
408
+ const a = new Array(2); // [undefined, undefined]
409
+ const b = new Array(2, 3); // [2, 3];
410
+ ```
411
+
412
+ Instead, always use bracket notation to initialize arrays, or `from` to initialize an `Array` with a certain size:
413
+
414
+ ```
415
+ const a = [2];
416
+ const b = [2, 3];
417
+
418
+ // Equivalent to Array(2):
419
+ const c = [];
420
+ c.length = 2;
421
+
422
+ // [0, 0, 0, 0, 0]
423
+ Array.from<number>({length: 5}).fill(0);
424
+ ```
425
+
426
+ #### Do not define properties on arrays
427
+
428
+ Do not define or use non-numeric properties on an array (other than `length` ). Use a `Map` (or `Object` ) instead.
429
+
430
+ #### Using spread syntax
431
+
432
+ Using spread syntax `[...foo];` is a convenient shorthand for shallow-copying or concatenating iterables.
433
+
434
+ ```
435
+ const foo = [
436
+ 1,
437
+ ];
438
+
439
+ const foo2 = [
440
+ ...foo,
441
+ 6,
442
+ 7,
443
+ ];
444
+
445
+ const foo3 = [
446
+ 5,
447
+ ...foo,
448
+ ];
449
+
450
+ foo2[1] === 6;
451
+ foo3[1] === 1;
452
+ ```
453
+
454
+ When using spread syntax, the value being spread *must* match what is being created. When creating an array, only spread iterables. Primitives (including `null` and `undefined` ) *must not* be spread.
455
+
456
+ ```
457
+ const foo = [7];
458
+ const bar = [5, ...(shouldUseFoo && foo)]; // might be undefined
459
+
460
+ // Creates {0: 'a', 1: 'b', 2: 'c'} but has no length
461
+ const fooStrings = ['a', 'b', 'c'];
462
+ const ids = {...fooStrings};
463
+ ```
464
+
465
+ ```
466
+ const foo = shouldUseFoo ? [7] : [];
467
+ const bar = [5, ...foo];
468
+ const fooStrings = ['a', 'b', 'c'];
469
+ const ids = [...fooStrings, 'd', 'e'];
470
+ ```
471
+
472
+ #### Array destructuring
473
+
474
+ Array literals may be used on the left-hand side of an assignment to perform destructuring (such as when unpacking multiple values from a single array or iterable). A final rest element may be included (with no space between the `...` and the variable name). Elements should be omitted if they are unused.
475
+
476
+ ```
477
+ const [a, b, c, ...rest] = generateResults();
478
+ let [, b,, d] = someArray;
479
+ ```
480
+
481
+ Destructuring may also be used for function parameters. Always specify `[]` as the default value if a destructured array parameter is optional, and provide default values on the left hand side:
482
+
483
+ ```
484
+ function destructured([a = 4, b = 2] = []) { ... }
485
+ ```
486
+
487
+ Disallowed:
488
+
489
+ ```
490
+ function badDestructuring([a, b] = [4, 2]) { ... }
491
+ ```
492
+
493
+ Tip: For (un)packing multiple values into a function's parameter or return, prefer object destructuring to array destructuring when possible, as it allows naming the individual elements and specifying a different type for each.
494
+
495
+ ### Object literals
496
+
497
+ #### Do not use the Object constructor
498
+
499
+ The `Object` constructor is disallowed. Use an object literal ( `{}` or `{a: 0, b: 1, c: 2}` ) instead.
500
+
501
+ #### Iterating objects
502
+
503
+ Iterating objects with `for (... in ...)` is error prone. It will include enumerable properties from the prototype chain.
504
+
505
+ Do not use unfiltered `for (... in ...)` statements:
506
+
507
+ ```
508
+ for (const x in someObj) {
509
+ // x could come from some parent prototype!
510
+ }
511
+ ```
512
+
513
+ Either filter values explicitly with an `if` statement, or use `for (... of Object.keys(...))` .
514
+
515
+ ```
516
+ for (const x in someObj) {
517
+ if (!someObj.hasOwnProperty(x)) continue;
518
+ // now x was definitely defined on someObj
519
+ }
520
+ for (const x of Object.keys(someObj)) { // note: for _of_!
521
+ // now x was definitely defined on someObj
522
+ }
523
+ for (const [key, value] of Object.entries(someObj)) { // note: for _of_!
524
+ // now key was definitely defined on someObj
525
+ }
526
+ ```
527
+
528
+ #### Using spread syntax
529
+
530
+ Using spread syntax `{...bar}` is a convenient shorthand for creating a shallow copy of an object. When using spread syntax in object initialization, later values replace earlier values at the same key.
531
+
532
+ ```
533
+ const foo = {
534
+ num: 1,
535
+ };
536
+
537
+ const foo2 = {
538
+ ...foo,
539
+ num: 5,
540
+ };
541
+
542
+ const foo3 = {
543
+ num: 5,
544
+ ...foo,
545
+ }
546
+
547
+ foo2.num === 5;
548
+ foo3.num === 1;
549
+ ```
550
+
551
+ When using spread syntax, the value being spread *must* match what is being created. That is, when creating an object, only objects may be spread; arrays and primitives (including `null` and `undefined` ) *must not* be spread. Avoid spreading objects that have prototypes other than the Object prototype (e.g. class definitions, class instances, functions) as the behavior is unintuitive (only enumerable non-prototype properties are shallow-copied).
552
+
553
+ ```
554
+ const foo = {num: 7};
555
+ const bar = {num: 5, ...(shouldUseFoo && foo)}; // might be undefined
556
+
557
+ // Creates {0: 'a', 1: 'b', 2: 'c'} but has no length
558
+ const fooStrings = ['a', 'b', 'c'];
559
+ const ids = {...fooStrings};
560
+ ```
561
+
562
+ ```
563
+ const foo = shouldUseFoo ? {num: 7} : {};
564
+ const bar = {num: 5, ...foo};
565
+ ```
566
+
567
+ #### Computed property names
568
+
569
+ Computed property names (e.g. `{['key' + foo()]: 42}` ) are allowed, and are considered dict-style (quoted) keys (i.e., must not be mixed with non-quoted keys) unless the computed property is a [symbol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) (e.g. `[Symbol.iterator]` ).
570
+
571
+ #### Object destructuring
572
+
573
+ Object destructuring patterns may be used on the left-hand side of an assignment to perform destructuring and unpack multiple values from a single object.
574
+
575
+ Destructured objects may also be used as function parameters, but should be kept as simple as possible: a single level of unquoted shorthand properties. Deeper levels of nesting and computed properties may not be used in parameter destructuring. Specify any default values in the left-hand-side of the destructured parameter ( `{str = 'some default'} = {}` , rather than `{str} = {str: 'some default'}` ), and if a destructured object is itself optional, it must default to `{}` .
576
+
577
+ Example:
578
+
579
+ ```
580
+ interface Options {
581
+ /** The number of times to do something. */
582
+ num?: number;
583
+
584
+ /** A string to do stuff to. */
585
+ str?: string;
586
+ }
587
+
588
+ function destructured({num, str = 'default'}: Options = {}) {}
589
+ ```
590
+
591
+ Disallowed:
592
+
593
+ ```
594
+ function nestedTooDeeply({x: {num, str}}: {x: Options}) {}
595
+ function nontrivialDefault({num, str}: Options = {num: 42, str: 'default'}) {}
596
+ ```
597
+
598
+ ### Classes
599
+
600
+ #### Class declarations
601
+
602
+ Class declarations *must not* be terminated with semicolons:
603
+
604
+ ```
605
+ class Foo {
606
+ }
607
+ ```
608
+
609
+ ```
610
+ class Foo {
611
+ }; // Unnecessary semicolon
612
+ ```
613
+
614
+ In contrast, statements that contain class expressions *must* be terminated with a semicolon:
615
+
616
+ ```
617
+ export const Baz = class extends Bar {
618
+ method(): number {
619
+ return this.x;
620
+ }
621
+ }; // Semicolon here as this is a statement, not a declaration
622
+ ```
623
+
624
+ ```
625
+ exports const Baz = class extends Bar {
626
+ method(): number {
627
+ return this.x;
628
+ }
629
+ }
630
+ ```
631
+
632
+ It is neither encouraged nor discouraged to have blank lines separating class declaration braces from other class content:
633
+
634
+ ```
635
+ // No spaces around braces - fine.
636
+ class Baz {
637
+ method(): number {
638
+ return this.x;
639
+ }
640
+ }
641
+
642
+ // A single space around both braces - also fine.
643
+ class Foo {
644
+
645
+ method(): number {
646
+ return this.x;
647
+ }
648
+
649
+ }
650
+ ```
651
+
652
+ #### Class method declarations
653
+
654
+ Class method declarations *must not* use a semicolon to separate individual method declarations:
655
+
656
+ ```
657
+ class Foo {
658
+ doThing() {
659
+ console.log("A");
660
+ }
661
+ }
662
+ ```
663
+
664
+ ```
665
+ class Foo {
666
+ doThing() {
667
+ console.log("A");
668
+ }; // <-- unnecessary
669
+ }
670
+ ```
671
+
672
+ Method declarations should be separated from surrounding code by a single blank line:
673
+
674
+ ```
675
+ class Foo {
676
+ doThing() {
677
+ console.log("A");
678
+ }
679
+
680
+ getOtherThing(): number {
681
+ return 4;
682
+ }
683
+ }
684
+ ```
685
+
686
+ ```
687
+ class Foo {
688
+ doThing() {
689
+ console.log("A");
690
+ }
691
+ getOtherThing(): number {
692
+ return 4;
693
+ }
694
+ }
695
+ ```
696
+
697
+ ##### Overriding toString
698
+
699
+ The `toString` method may be overridden, but must always succeed and never have visible side effects.
700
+
701
+ Tip: Beware, in particular, of calling other methods from toString, since exceptional conditions could lead to infinite loops.
702
+
703
+ #### Static methods
704
+
705
+ ##### Avoid private static methods
706
+
707
+ Where it does not interfere with readability, prefer module-local functions over private static methods.
708
+
709
+ ##### Do not rely on dynamic dispatch
710
+
711
+ Code *should not* rely on dynamic dispatch of static methods. Static methods *should* only be called on the base class itself (which defines it directly). Static methods *should not* be called on variables containing a dynamic instance that may be either the constructor or a subclass constructor (and *must* be defined with `@nocollapse` if this is done), and *must not* be called directly on a subclass that doesn't define the method itself.
712
+
713
+ Disallowed:
714
+
715
+ ```
716
+ // Context for the examples below (this class is okay by itself)
717
+ class Base {
718
+ /** @nocollapse */ static foo() {}
719
+ }
720
+ class Sub extends Base {}
721
+
722
+ // Discouraged: don't call static methods dynamically
723
+ function callFoo(cls: typeof Base) {
724
+ cls.foo();
725
+ }
726
+
727
+ // Disallowed: don't call static methods on subclasses that don't define it themselves
728
+ Sub.foo();
729
+
730
+ // Disallowed: don't access this in static methods.
731
+ class MyClass {
732
+ static foo() {
733
+ return this.staticField;
734
+ }
735
+ }
736
+ MyClass.staticField = 1;
737
+ ```
738
+
739
+ ##### Avoid static this references
740
+
741
+ Code *must not* use `this` in a static context.
742
+
743
+ JavaScript allows accessing static fields through `this` . Different from other languages, static fields are also inherited.
744
+
745
+ ```
746
+ class ShoeStore {
747
+ static storage: Storage = ...;
748
+
749
+ static isAvailable(s: Shoe) {
750
+ // Bad: do not use `this` in a static method.
751
+ return this.storage.has(s.id);
752
+ }
753
+ }
754
+
755
+ class EmptyShoeStore extends ShoeStore {
756
+ static storage: Storage = EMPTY_STORE; // overrides storage from ShoeStore
757
+ }
758
+ ```
759
+
760
+ Why?
761
+
762
+ This code is generally surprising: authors might not expect that static fields can be accessed through the this pointer, and might be surprised to find that they can be overridden - this feature is not commonly used.
763
+
764
+ This code also encourages an anti-pattern of having substantial static state, which causes problems with testability.
765
+
766
+ #### Constructors
767
+
768
+ Constructor calls *must* use parentheses, even when no arguments are passed:
769
+
770
+ ```
771
+ const x = new Foo;
772
+ ```
773
+
774
+ ```
775
+ const x = new Foo();
776
+ ```
777
+
778
+ Omitting parentheses can lead to subtle mistakes. These two lines are not equivalent:
779
+
780
+ ```
781
+ new Foo().Bar();
782
+ new Foo.Bar();
783
+ ```
784
+
785
+ It is unnecessary to provide an empty constructor or one that simply delegates into its parent class because ES2015 provides a default class constructor if one is not specified. However constructors with parameter properties, visibility modifiers or parameter decorators *should not* be omitted even if the body of the constructor is empty.
786
+
787
+ ```
788
+ class UnnecessaryConstructor {
789
+ constructor() {}
790
+ }
791
+ ```
792
+
793
+ ```
794
+ class UnnecessaryConstructorOverride extends Base {
795
+ constructor(value: number) {
796
+ super(value);
797
+ }
798
+ }
799
+ ```
800
+
801
+ ```
802
+ class DefaultConstructor {
803
+ }
804
+
805
+ class ParameterProperties {
806
+ constructor(private myService) {}
807
+ }
808
+
809
+ class ParameterDecorators {
810
+ constructor(@SideEffectDecorator myService) {}
811
+ }
812
+
813
+ class NoInstantiation {
814
+ private constructor() {}
815
+ }
816
+ ```
817
+
818
+ The constructor should be separated from surrounding code both above and below by a single blank line:
819
+
820
+ ```
821
+ class Foo {
822
+ myField = 10;
823
+
824
+ constructor(private readonly ctorParam) {}
825
+
826
+ doThing() {
827
+ console.log(ctorParam.getThing() + myField);
828
+ }
829
+ }
830
+ ```
831
+
832
+ ```
833
+ class Foo {
834
+ myField = 10;
835
+ constructor(private readonly ctorParam) {}
836
+ doThing() {
837
+ console.log(ctorParam.getThing() + myField);
838
+ }
839
+ }
840
+ ```
841
+
842
+ #### Class members
843
+
844
+ ##### No #private fields
845
+
846
+ Do not use private fields (also known as private identifiers):
847
+
848
+ ```
849
+ class Clazz {
850
+ #ident = 1;
851
+ }
852
+ ```
853
+
854
+ Instead, use TypeScript's visibility annotations:
855
+
856
+ ```
857
+ class Clazz {
858
+ private ident = 1;
859
+ }
860
+ ```
861
+
862
+ Why?
863
+
864
+ Private identifiers cause substantial emit size and performance regressions when down-leveled by TypeScript, and are unsupported before ES2015. They can only be downleveled to ES2015, not lower. At the same time, they do not offer substantial benefits when static type checking is used to enforce visibility.
865
+
866
+ ##### Use readonly
867
+
868
+ Mark properties that are never reassigned outside of the constructor with the `readonly` modifier (these need not be deeply immutable).
869
+
870
+ ##### Parameter properties
871
+
872
+ Rather than plumbing an obvious initializer through to a class member, use a TypeScript [parameter property](https://www.typescriptlang.org/docs/handbook/2/classes.html#parameter-properties) .
873
+
874
+ ```
875
+ class Foo {
876
+ private readonly barService: BarService;
877
+
878
+ constructor(barService: BarService) {
879
+ this.barService = barService;
880
+ }
881
+ }
882
+ ```
883
+
884
+ ```
885
+ class Foo {
886
+ constructor(private readonly barService: BarService) {}
887
+ }
888
+ ```
889
+
890
+ If the parameter property needs documentation, [use an](#parameter-property-comments) [`@param`](#parameter-property-comments) [JSDoc tag](#parameter-property-comments) .
891
+
892
+ ##### Field initializers
893
+
894
+ If a class member is not a parameter, initialize it where it's declared, which sometimes lets you drop the constructor entirely.
895
+
896
+ ```
897
+ class Foo {
898
+ private readonly userList: string[];
899
+
900
+ constructor() {
901
+ this.userList = [];
902
+ }
903
+ }
904
+ ```
905
+
906
+ ```
907
+ class Foo {
908
+ private readonly userList: string[] = [];
909
+ }
910
+ ```
911
+
912
+ Tip: Properties should never be added to or removed from an instance after the constructor is finished, since it significantly hinders VMs' ability to optimize classes' shape . Optional fields that may be filled in later should be explicitly initialized to `undefined` to prevent later shape changes.
913
+
914
+ ##### Properties used outside of class lexical scope
915
+
916
+ Properties used from outside the lexical scope of their containing class, such as an Angular component's properties used from a template, *must not* use `private` visibility, as they are used outside of the lexical scope of their containing class.
917
+
918
+ Use either `protected` or `public` as appropriate to the property in question. Angular and AngularJS template properties should use `protected` , but Polymer should use `public` .
919
+
920
+ TypeScript code *must not* use `obj['foo']` to bypass the visibility of a property.
921
+
922
+ Why?
923
+
924
+ When a property is `private` , you are declaring to both automated systems and humans that the property accesses are scoped to the methods of the declaring class, and they will rely on that. For example, a check for unused code will flag a private property that appears to be unused, even if some other file manages to bypass the visibility restriction.
925
+
926
+ Though it might appear that `obj['foo']` can bypass visibility in the TypeScript compiler, this pattern can be broken by rearranging the build rules, and also violates [optimization compatibility](#optimization-compatibility) .
927
+
928
+ ##### Getters and setters
929
+
930
+ Getters and setters, also known as accessors, for class members *may* be used. The getter method *must* be a [pure function](https://en.wikipedia.org/wiki/Pure_function) (i.e., result is consistent and has no side effects: getters *must not* change observable state). They are also useful as a means of restricting the visibility of internal or verbose implementation details (shown below).
931
+
932
+ ```
933
+ class Foo {
934
+ constructor(private readonly someService: SomeService) {}
935
+
936
+ get someMember(): string {
937
+ return this.someService.someVariable;
938
+ }
939
+
940
+ set someMember(newValue: string) {
941
+ this.someService.someVariable = newValue;
942
+ }
943
+ }
944
+ ```
945
+
946
+ ```
947
+ class Foo {
948
+ nextId = 0;
949
+ get next() {
950
+ return this.nextId++; // Bad: getter changes observable state
951
+ }
952
+ }
953
+ ```
954
+
955
+ If an accessor is used to hide a class property, the hidden property *may* be prefixed or suffixed with any whole word, like `internal` or `wrapped` . When using these private properties, access the value through the accessor whenever possible. At least one accessor for a property *must* be non-trivial: do not define pass-through accessors only for the purpose of hiding a property. Instead, make the property public (or consider making it `readonly` rather than just defining a getter with no setter).
956
+
957
+ ```
958
+ class Foo {
959
+ private wrappedBar = '';
960
+ get bar() {
961
+ return this.wrappedBar || 'bar';
962
+ }
963
+
964
+ set bar(wrapped: string) {
965
+ this.wrappedBar = wrapped.trim();
966
+ }
967
+ }
968
+ ```
969
+
970
+ ```
971
+ class Bar {
972
+ private barInternal = '';
973
+ // Neither of these accessors have logic, so just make bar public.
974
+ get bar() {
975
+ return this.barInternal;
976
+ }
977
+
978
+ set bar(value: string) {
979
+ this.barInternal = value;
980
+ }
981
+ }
982
+ ```
983
+
984
+ Getters and setters *must not* be defined using `Object.defineProperty` , since this interferes with property renaming.
985
+
986
+ ##### Computed properties
987
+
988
+ Computed properties may only be used in classes when the property is a symbol. Dict-style properties (that is, quoted or computed non-symbol keys) are not allowed (see [rationale for not mixing key types](#features-objects-mixing-keys) . A `[Symbol.iterator]` method should be defined for any classes that are logically iterable. Beyond this, `Symbol` should be used sparingly.
989
+
990
+ Tip: be careful of using any other built-in symbols (e.g. `Symbol.isConcatSpreadable` ) as they are not polyfilled by the compiler and will therefore not work in older browsers.
991
+
992
+ #### Visibility
993
+
994
+ Restricting visibility of properties, methods, and entire types helps with keeping code decoupled.
995
+
996
+ - Limit symbol visibility as much as possible.
997
+ - Consider converting private methods to non-exported functions within the same file but outside of any class, and moving private properties into a separate, non-exported class.
998
+ - TypeScript symbols are public by default. Never use the `public` modifier except when declaring non-readonly public parameter properties (in constructors).
999
+
1000
+ ```
1001
+ class Foo {
1002
+ public bar = new Bar(); // BAD: public modifier not needed
1003
+
1004
+ constructor(public readonly baz: Baz) {} // BAD: readonly implies it's a property which defaults to public
1005
+ }
1006
+ ```
1007
+
1008
+ ```
1009
+ class Foo {
1010
+ bar = new Bar(); // GOOD: public modifier not needed
1011
+
1012
+ constructor(public baz: Baz) {} // public modifier allowed
1013
+ }
1014
+ ```
1015
+
1016
+ See also [export visibility](#export-visibility) .
1017
+
1018
+ #### Disallowed class patterns
1019
+
1020
+ ##### Do not manipulate prototype s directly
1021
+
1022
+ The `class` keyword allows clearer and more readable class definitions than defining `prototype` properties. Ordinary implementation code has no business manipulating these objects. Mixins and modifying the prototypes of builtin objects are explicitly forbidden.
1023
+
1024
+ **Exception** : Framework code (such as Polymer, or Angular) may need to use `prototype` s, and should not resort to even-worse workarounds to avoid doing so.
1025
+
1026
+ ### Functions
1027
+
1028
+ #### Terminology
1029
+
1030
+ There are many different types of functions, with subtle distinctions between them. This guide uses the following terminology, which aligns with [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions) :
1031
+
1032
+ - function declaration : a declaration (i.e. not an expression) using the `function` keyword
1033
+ - function expression : an expression, typically used in an assignment or passed as a parameter, using the `function` keyword
1034
+ - arrow function : an expression using the `=>` syntax
1035
+ - block body : right hand side of an arrow function with braces
1036
+ - concise body : right hand side of an arrow function without braces
1037
+
1038
+ Methods and classes/constructors are not covered in this section.
1039
+
1040
+ #### Prefer function declarations for named functions
1041
+
1042
+ Prefer function declarations over arrow functions or function expressions when defining named functions.
1043
+
1044
+ ```
1045
+ function foo() {
1046
+ return 42;
1047
+ }
1048
+ ```
1049
+
1050
+ ```
1051
+ const foo = () => 42;
1052
+ ```
1053
+
1054
+ Arrow functions *may* be used, for example, when an explicit type annotation is required.
1055
+
1056
+ ```
1057
+ interface SearchFunction {
1058
+ (source: string, subString: string): boolean;
1059
+ }
1060
+
1061
+ const fooSearch: SearchFunction = (source, subString) => { ... };
1062
+ ```
1063
+
1064
+ #### Nested functions
1065
+
1066
+ Functions nested within other methods or functions *may* use function declarations or arrow functions, as appropriate. In method bodies in particular, arrow functions are preferred because they have access to the outer `this` .
1067
+
1068
+ #### Do not use function expressions
1069
+
1070
+ Do not use function expressions. Use arrow functions instead.
1071
+
1072
+ ```
1073
+ bar(() => { this.doSomething(); })
1074
+ ```
1075
+
1076
+ ```
1077
+ bar(function() { ... })
1078
+ ```
1079
+
1080
+ **Exception:** Function expressions *may* be used *only if* code has to dynamically rebind `this` (but this is [discouraged](#rebinding-this) ), or for generator functions (which do not have an arrow syntax).
1081
+
1082
+ #### Arrow function bodies
1083
+
1084
+ Use arrow functions with concise bodies (i.e. expressions) or block bodies as appropriate.
1085
+
1086
+ ```
1087
+ // Top level functions use function declarations.
1088
+ function someFunction() {
1089
+ // Block bodies are fine:
1090
+ const receipts = books.map((b: Book) => {
1091
+ const receipt = payMoney(b.price);
1092
+ recordTransaction(receipt);
1093
+ return receipt;
1094
+ });
1095
+
1096
+ // Concise bodies are fine, too, if the return value is used:
1097
+ const longThings = myValues.filter(v => v.length > 1000).map(v => String(v));
1098
+
1099
+ function payMoney(amount: number) {
1100
+ // function declarations are fine, but must not access `this`.
1101
+ }
1102
+
1103
+ // Nested arrow functions may be assigned to a const.
1104
+ const computeTax = (amount: number) => amount * 0.12;
1105
+ }
1106
+ ```
1107
+
1108
+ Only use a concise body if the return value of the function is actually used. The block body makes sure the return type is `void` then and prevents potential side effects.
1109
+
1110
+ ```
1111
+ // BAD: use a block body if the return value of the function is not used.
1112
+ myPromise.then(v => console.log(v));
1113
+ // BAD: this typechecks, but the return value still leaks.
1114
+ let f: () => void;
1115
+ f = () => 1;
1116
+ ```
1117
+
1118
+ ```
1119
+ // GOOD: return value is unused, use a block body.
1120
+ myPromise.then(v => {
1121
+ console.log(v);
1122
+ });
1123
+ // GOOD: code may use blocks for readability.
1124
+ const transformed = [1, 2, 3].map(v => {
1125
+ const intermediate = someComplicatedExpr(v);
1126
+ const more = acrossManyLines(intermediate);
1127
+ return worthWrapping(more);
1128
+ });
1129
+ // GOOD: explicit `void` ensures no leaked return value
1130
+ myPromise.then(v => void console.log(v));
1131
+ ```
1132
+
1133
+ Tip: The `void` operator can be used to ensure an arrow function with an expression body returns `undefined` when the result is unused.
1134
+
1135
+ #### Rebinding this
1136
+
1137
+ Function expressions and function declarations *must not* use `this` unless they specifically exist to rebind the `this` pointer. Rebinding `this` can in most cases be avoided by using arrow functions or explicit parameters.
1138
+
1139
+ ```
1140
+ function clickHandler() {
1141
+ // Bad: what's `this` in this context?
1142
+ this.textContent = 'Hello';
1143
+ }
1144
+ // Bad: the `this` pointer reference is implicitly set to document.body.
1145
+ document.body.onclick = clickHandler;
1146
+ ```
1147
+
1148
+ ```
1149
+ // Good: explicitly reference the object from an arrow function.
1150
+ document.body.onclick = () => { document.body.textContent = 'hello'; };
1151
+ // Alternatively: take an explicit parameter
1152
+ const setTextFn = (e: HTMLElement) => { e.textContent = 'hello'; };
1153
+ document.body.onclick = setTextFn.bind(null, document.body);
1154
+ ```
1155
+
1156
+ Prefer arrow functions over other approaches to binding `this` , such as `f.bind(this)` , `goog.bind(f, this)` , or `const self = this` .
1157
+
1158
+ #### Prefer passing arrow functions as callbacks
1159
+
1160
+ Callbacks can be invoked with unexpected arguments that can pass a type check but still result in logical errors.
1161
+
1162
+ Avoid passing a named callback to a higher-order function, unless you are sure of the stability of both functions' call signatures. Beware, in particular, of less-commonly-used optional parameters.
1163
+
1164
+ ```
1165
+ // BAD: Arguments are not explicitly passed, leading to unintended behavior
1166
+ // when the optional `radix` argument gets the array indices 0, 1, and 2.
1167
+ const numbers = ['11', '5', '10'].map(parseInt);
1168
+ // > [11, NaN, 2];
1169
+ ```
1170
+
1171
+ Instead, prefer passing an arrow-function that explicitly forwards parameters to the named callback.
1172
+
1173
+ ```
1174
+ // GOOD: Arguments are explicitly passed to the callback
1175
+ const numbers = ['11', '5', '3'].map((n) => parseInt(n));
1176
+ // > [11, 5, 3]
1177
+
1178
+ // GOOD: Function is locally defined and is designed to be used as a callback
1179
+ function dayFilter(element: string|null|undefined) {
1180
+ return element != null && element.endsWith('day');
1181
+ }
1182
+
1183
+ const days = ['tuesday', undefined, 'juice', 'wednesday'].filter(dayFilter);
1184
+ ```
1185
+
1186
+ #### Arrow functions as properties
1187
+
1188
+ Classes usually *should not* contain properties initialized to arrow functions. Arrow function properties require the calling function to understand that the callee's `this` is already bound, which increases confusion about what `this` is, and call sites and references using such handlers look broken (i.e. require non-local knowledge to determine that they are correct). Code *should* always use arrow functions to call instance methods ( `const handler = (x) => { this.listener(x); };` ), and *should not* obtain or pass references to instance methods ( ~~`const handler = this.listener; handler(x);`~~ ).
1189
+
1190
+ Note: in some specific situations, e.g. when binding functions in a template, arrow functions as properties are useful and create much more readable code. Use judgement with this rule. Also, see the [`Event Handlers`](#event-handlers) section below.
1191
+
1192
+ ```
1193
+ class DelayHandler {
1194
+ constructor() {
1195
+ // Problem: `this` is not preserved in the callback. `this` in the callback
1196
+ // will not be an instance of DelayHandler.
1197
+ setTimeout(this.patienceTracker, 5000);
1198
+ }
1199
+ private patienceTracker() {
1200
+ this.waitedPatiently = true;
1201
+ }
1202
+ }
1203
+ ```
1204
+
1205
+ ```
1206
+ // Arrow functions usually should not be properties.
1207
+ class DelayHandler {
1208
+ constructor() {
1209
+ // Bad: this code looks like it forgot to bind `this`.
1210
+ setTimeout(this.patienceTracker, 5000);
1211
+ }
1212
+ private patienceTracker = () => {
1213
+ this.waitedPatiently = true;
1214
+ }
1215
+ }
1216
+ ```
1217
+
1218
+ ```
1219
+ // Explicitly manage `this` at call time.
1220
+ class DelayHandler {
1221
+ constructor() {
1222
+ // Use anonymous functions if possible.
1223
+ setTimeout(() => {
1224
+ this.patienceTracker();
1225
+ }, 5000);
1226
+ }
1227
+ private patienceTracker() {
1228
+ this.waitedPatiently = true;
1229
+ }
1230
+ }
1231
+ ```
1232
+
1233
+ #### Event handlers
1234
+
1235
+ Event handlers *may* use arrow functions when there is no need to uninstall the handler (for example, if the event is emitted by the class itself). If the handler requires uninstallation, arrow function properties are the right approach, because they automatically capture `this` and provide a stable reference to uninstall.
1236
+
1237
+ ```
1238
+ // Event handlers may be anonymous functions or arrow function properties.
1239
+ class Component {
1240
+ onAttached() {
1241
+ // The event is emitted by this class, no need to uninstall.
1242
+ this.addEventListener('click', () => {
1243
+ this.listener();
1244
+ });
1245
+ // this.listener is a stable reference, we can uninstall it later.
1246
+ window.addEventListener('onbeforeunload', this.listener);
1247
+ }
1248
+ onDetached() {
1249
+ // The event is emitted by window. If we don't uninstall, this.listener will
1250
+ // keep a reference to `this` because it's bound, causing a memory leak.
1251
+ window.removeEventListener('onbeforeunload', this.listener);
1252
+ }
1253
+ // An arrow function stored in a property is bound to `this` automatically.
1254
+ private listener = () => {
1255
+ confirm('Do you want to exit the page?');
1256
+ }
1257
+ }
1258
+ ```
1259
+
1260
+ Do not use `bind` in the expression that installs an event handler, because it creates a temporary reference that can't be uninstalled.
1261
+
1262
+ ```
1263
+ // Binding listeners creates a temporary reference that prevents uninstalling.
1264
+ class Component {
1265
+ onAttached() {
1266
+ // This creates a temporary reference that we won't be able to uninstall
1267
+ window.addEventListener('onbeforeunload', this.listener.bind(this));
1268
+ }
1269
+ onDetached() {
1270
+ // This bind creates a different reference, so this line does nothing.
1271
+ window.removeEventListener('onbeforeunload', this.listener.bind(this));
1272
+ }
1273
+ private listener() {
1274
+ confirm('Do you want to exit the page?');
1275
+ }
1276
+ }
1277
+ ```
1278
+
1279
+ #### Parameter initializers
1280
+
1281
+ Optional function parameters *may* be given a default initializer to use when the argument is omitted. Initializers *must not* have any observable side effects. Initializers *should* be kept as simple as possible.
1282
+
1283
+ ```
1284
+ function process(name: string, extraContext: string[] = []) {}
1285
+ function activate(index = 0) {}
1286
+ ```
1287
+
1288
+ ```
1289
+ // BAD: side effect of incrementing the counter
1290
+ let globalCounter = 0;
1291
+ function newId(index = globalCounter++) {}
1292
+
1293
+ // BAD: exposes shared mutable state, which can introduce unintended coupling
1294
+ // between function calls
1295
+ class Foo {
1296
+ private readonly defaultPaths: string[];
1297
+ frobnicate(paths = defaultPaths) {}
1298
+ }
1299
+ ```
1300
+
1301
+ Use default parameters sparingly. Prefer [destructuring](#features-objects-destructuring) to create readable APIs when there are more than a small handful of optional parameters that do not have a natural order.
1302
+
1303
+ #### Prefer rest and spread when appropriate
1304
+
1305
+ Use a *rest* parameter instead of accessing `arguments` . Never name a local variable or parameter `arguments` , which confusingly shadows the built-in name.
1306
+
1307
+ ```
1308
+ function variadic(array: string[], ...numbers: number[]) {}
1309
+ ```
1310
+
1311
+ Use function spread syntax instead of `Function.prototype.apply` .
1312
+
1313
+ #### Formatting functions
1314
+
1315
+ Blank lines at the start or end of the function body are not allowed.
1316
+
1317
+ A single blank line *may* be used within function bodies sparingly to create *logical groupings* of statements.
1318
+
1319
+ Generators should attach the `*` to the `function` and `yield` keywords, as in `function* foo()` and `yield* iter` , rather than ~~`function *foo()`~~ or ~~`yield *iter`~~ .
1320
+
1321
+ Parentheses around the left-hand side of a single-argument arrow function are recommended but not required.
1322
+
1323
+ Do not put a space after the `...` in rest or spread syntax.
1324
+
1325
+ ```
1326
+ function myFunction(...elements: number[]) {}
1327
+ myFunction(...array, ...iterable, ...generator());
1328
+ ```
1329
+
1330
+ ### this
1331
+
1332
+ Only use `this` in class constructors and methods, functions that have an explicit `this` type declared (e.g. `function func(this: ThisType, ...)` ), or in arrow functions defined in a scope where `this` may be used.
1333
+
1334
+ Never use `this` to refer to the global object, the context of an `eval` , the target of an event, or unnecessarily `call()` ed or `apply()` ed functions.
1335
+
1336
+ ```
1337
+ this.alert('Hello');
1338
+ ```
1339
+
1340
+ ### Interfaces
1341
+
1342
+ ### Primitive literals
1343
+
1344
+ #### String literals
1345
+
1346
+ ##### Use single quotes
1347
+
1348
+ Ordinary string literals are delimited with single quotes ( `'` ), rather than double quotes ( `"` ).
1349
+
1350
+ Tip: if a string contains a single quote character, consider using a template string to avoid having to escape the quote.
1351
+
1352
+ ##### No line continuations
1353
+
1354
+ Do not use *line continuations* (that is, ending a line inside a string literal with a backslash) in either ordinary or template string literals. Even though ES5 allows this, it can lead to tricky errors if any trailing whitespace comes after the slash, and is less obvious to readers.
1355
+
1356
+ Disallowed:
1357
+
1358
+ ```
1359
+ const LONG_STRING = 'This is a very very very very very very very long string. \
1360
+ It inadvertently contains long stretches of spaces due to how the \
1361
+ continued lines are indented.';
1362
+ ```
1363
+
1364
+ Instead, write
1365
+
1366
+ ```
1367
+ const LONG_STRING = 'This is a very very very very very very long string. ' +
1368
+ 'It does not contain long stretches of spaces because it uses ' +
1369
+ 'concatenated strings.';
1370
+ const SINGLE_STRING =
1371
+ 'http://it.is.also/acceptable_to_use_a_single_long_string_when_breaking_would_hinder_search_discoverability';
1372
+ ```
1373
+
1374
+ ##### Template literals
1375
+
1376
+ Use template literals (delimited with ``` ) over complex string concatenation, particularly if multiple string literals are involved. Template literals may span multiple lines.
1377
+
1378
+ If a template literal spans multiple lines, it does not need to follow the indentation of the enclosing block, though it may if the added whitespace does not matter.
1379
+
1380
+ Example:
1381
+
1382
+ ```
1383
+ function arithmetic(a: number, b: number) {
1384
+ return `Here is a table of arithmetic operations:
1385
+ ${a} + ${b} = ${a + b}
1386
+ ${a} - ${b} = ${a - b}
1387
+ ${a} * ${b} = ${a * b}
1388
+ ${a} / ${b} = ${a / b}`;
1389
+ }
1390
+ ```
1391
+
1392
+ #### Number literals
1393
+
1394
+ Numbers may be specified in decimal, hex, octal, or binary. Use exactly `0x` , `0o` , and `0b` prefixes, with lowercase letters, for hex, octal, and binary, respectively. Never include a leading zero unless it is immediately followed by `x` , `o` , or `b` .
1395
+
1396
+ #### Type coercion
1397
+
1398
+ TypeScript code *may* use the `String()` and `Boolean()` (note: no `new` !) functions, string template literals, or `!!` to coerce types.
1399
+
1400
+ ```
1401
+ const bool = Boolean(false);
1402
+ const str = String(aNumber);
1403
+ const bool2 = !!str;
1404
+ const str2 = `result: ${bool2}`;
1405
+ ```
1406
+
1407
+ Values of enum types (including unions of enum types and other types) *must not* be converted to booleans with `Boolean()` or `!!` , and must instead be compared explicitly with comparison operators.
1408
+
1409
+ ```
1410
+ enum SupportLevel {
1411
+ NONE,
1412
+ BASIC,
1413
+ ADVANCED,
1414
+ }
1415
+
1416
+ const level: SupportLevel = ...;
1417
+ let enabled = Boolean(level);
1418
+
1419
+ const maybeLevel: SupportLevel|undefined = ...;
1420
+ enabled = !!maybeLevel;
1421
+ ```
1422
+
1423
+ ```
1424
+ enum SupportLevel {
1425
+ NONE,
1426
+ BASIC,
1427
+ ADVANCED,
1428
+ }
1429
+
1430
+ const level: SupportLevel = ...;
1431
+ let enabled = level !== SupportLevel.NONE;
1432
+
1433
+ const maybeLevel: SupportLevel|undefined = ...;
1434
+ enabled = level !== undefined && level !== SupportLevel.NONE;
1435
+ ```
1436
+
1437
+ Why?
1438
+
1439
+ For most purposes, it doesn't matter what number or string value an enum name is mapped to at runtime, because values of enum types are referred to by name in source code. Consequently, engineers are accustomed to not thinking about this, and so situations where it *does* matter are undesirable because they will be surprising. Such is the case with conversion of enums to booleans; in particular, by default, the first declared enum value is falsy (because it is 0) while the others are truthy, which is likely to be unexpected. Readers of code that uses an enum value may not even know whether it's the first declared value or not.
1440
+
1441
+ Using string concatenation to cast to string is discouraged, as we check that operands to the plus operator are of matching types.
1442
+
1443
+ Code *must* use `Number()` to parse numeric values, and *must* check its return for `NaN` values explicitly, unless failing to parse is impossible from context.
1444
+
1445
+ Note: `Number('')` , `Number(' ')` , and `Number('\t')` would return `0` instead of `NaN` . `Number('Infinity')` and `Number('-Infinity')` would return `Infinity` and `-Infinity` respectively. Additionally, exponential notation such as `Number('1e+309')` and `Number('-1e+309')` can overflow into `Infinity` . These cases may require special handling.
1446
+
1447
+ ```
1448
+ const aNumber = Number('123');
1449
+ if (!isFinite(aNumber)) throw new Error(...);
1450
+ ```
1451
+
1452
+ Code *must not* use unary plus ( `+` ) to coerce strings to numbers. Parsing numbers can fail, has surprising corner cases, and can be a code smell (parsing at the wrong layer). A unary plus is too easy to miss in code reviews given this.
1453
+
1454
+ ```
1455
+ const x = +y;
1456
+ ```
1457
+
1458
+ Code also *must not* use `parseInt` or `parseFloat` to parse numbers, except for non-base-10 strings (see below). Both of those functions ignore trailing characters in the string, which can shadow error conditions (e.g. parsing `12 dwarves` as `12` ).
1459
+
1460
+ ```
1461
+ const n = parseInt(someString, 10); // Error prone,
1462
+ const f = parseFloat(someString); // regardless of passing a radix.
1463
+ ```
1464
+
1465
+ Code that requires parsing with a radix *must* check that its input contains only appropriate digits for that radix before calling into `parseInt` ;
1466
+
1467
+ ```
1468
+ if (!/^[a-fA-F0-9]+$/.test(someString)) throw new Error(...);
1469
+ // Needed to parse hexadecimal.
1470
+ // tslint:disable-next-line:ban
1471
+ const n = parseInt(someString, 16); // Only allowed for radix != 10
1472
+ ```
1473
+
1474
+ Use `Number()` followed by `Math.floor` or `Math.trunc` (where available) to parse integer numbers:
1475
+
1476
+ ```
1477
+ let f = Number(someString);
1478
+ if (isNaN(f)) handleError();
1479
+ f = Math.floor(f);
1480
+ ```
1481
+
1482
+ ##### Implicit coercion
1483
+
1484
+ Do not use explicit boolean coercions in conditional clauses that have implicit boolean coercion. Those are the conditions in an `if` , `for` and `while` statements.
1485
+
1486
+ ```
1487
+ const foo: MyInterface|null = ...;
1488
+ if (!!foo) {...}
1489
+ while (!!foo) {...}
1490
+ ```
1491
+
1492
+ ```
1493
+ const foo: MyInterface|null = ...;
1494
+ if (foo) {...}
1495
+ while (foo) {...}
1496
+ ```
1497
+
1498
+ [As with explicit conversions](#type-coercion) , values of enum types (including unions of enum types and other types) *must not* be implicitly coerced to booleans, and must instead be compared explicitly with comparison operators.
1499
+
1500
+ ```
1501
+ enum SupportLevel {
1502
+ NONE,
1503
+ BASIC,
1504
+ ADVANCED,
1505
+ }
1506
+
1507
+ const level: SupportLevel = ...;
1508
+ if (level) {...}
1509
+
1510
+ const maybeLevel: SupportLevel|undefined = ...;
1511
+ if (level) {...}
1512
+ ```
1513
+
1514
+ ```
1515
+ enum SupportLevel {
1516
+ NONE,
1517
+ BASIC,
1518
+ ADVANCED,
1519
+ }
1520
+
1521
+ const level: SupportLevel = ...;
1522
+ if (level !== SupportLevel.NONE) {...}
1523
+
1524
+ const maybeLevel: SupportLevel|undefined = ...;
1525
+ if (level !== undefined && level !== SupportLevel.NONE) {...}
1526
+ ```
1527
+
1528
+ Other types of values may be either implicitly coerced to booleans or compared explicitly with comparison operators:
1529
+
1530
+ ```
1531
+ // Explicitly comparing > 0 is OK:
1532
+ if (arr.length > 0) {...}
1533
+ // so is relying on boolean coercion:
1534
+ if (arr.length) {...}
1535
+ ```
1536
+
1537
+ ### Control structures
1538
+
1539
+ #### Control flow statements and blocks
1540
+
1541
+ Control flow statements ( `if` , `else` , `for` , `do` , `while` , etc) always use braced blocks for the containing code, even if the body contains only a single statement. The first statement of a non-empty block must begin on its own line.
1542
+
1543
+ ```
1544
+ for (let i = 0; i < x; i++) {
1545
+ doSomethingWith(i);
1546
+ }
1547
+
1548
+ if (x) {
1549
+ doSomethingWithALongMethodNameThatForcesANewLine(x);
1550
+ }
1551
+ ```
1552
+
1553
+ ```
1554
+ if (x)
1555
+ doSomethingWithALongMethodNameThatForcesANewLine(x);
1556
+
1557
+ for (let i = 0; i < x; i++) doSomethingWith(i);
1558
+ ```
1559
+
1560
+ **Exception:** `if` statements fitting on one line *may* elide the block.
1561
+
1562
+ ```
1563
+ if (x) x.doFoo();
1564
+ ```
1565
+
1566
+ ##### Assignment in control statements
1567
+
1568
+ Prefer to avoid assignment of variables inside control statements. Assignment can be easily mistaken for equality checks inside control statements.
1569
+
1570
+ ```
1571
+ if (x = someFunction()) {
1572
+ // Assignment easily mistaken with equality check
1573
+ // ...
1574
+ }
1575
+ ```
1576
+
1577
+ ```
1578
+ x = someFunction();
1579
+ if (x) {
1580
+ // ...
1581
+ }
1582
+ ```
1583
+
1584
+ In cases where assignment inside the control statement is preferred, enclose the assignment in additional parenthesis to indicate it is intentional.
1585
+
1586
+ ```
1587
+ while ((x = someFunction())) {
1588
+ // Double parenthesis shows assignment is intentional
1589
+ // ...
1590
+ }
1591
+ ```
1592
+
1593
+ ##### Iterating containers
1594
+
1595
+ Prefer `for (... of someArr)` to iterate over arrays. `Array.prototype.forEach` and vanilla `for` loops are also allowed:
1596
+
1597
+ ```
1598
+ for (const x of someArr) {
1599
+ // x is a value of someArr.
1600
+ }
1601
+
1602
+ for (let i = 0; i < someArr.length; i++) {
1603
+ // Explicitly count if the index is needed, otherwise use the for/of form.
1604
+ const x = someArr[i];
1605
+ // ...
1606
+ }
1607
+ for (const [i, x] of someArr.entries()) {
1608
+ // Alternative version of the above.
1609
+ }
1610
+ ```
1611
+
1612
+ `for` - `in` loops may only be used on dict-style objects (see [below](#optimization-compatibility-for-property-access) for more info). Do not use `for (... in ...)` to iterate over arrays as it will counterintuitively give the array's indices (as strings!), not values:
1613
+
1614
+ ```
1615
+ for (const x in someArray) {
1616
+ // x is the index!
1617
+ }
1618
+ ```
1619
+
1620
+ `Object.prototype.hasOwnProperty` should be used in `for` - `in` loops to exclude unwanted prototype properties. Prefer `for` - `of` with `Object.keys` , `Object.values` , or `Object.entries` over `for` - `in` when possible.
1621
+
1622
+ ```
1623
+ for (const key in obj) {
1624
+ if (!obj.hasOwnProperty(key)) continue;
1625
+ doWork(key, obj[key]);
1626
+ }
1627
+ for (const key of Object.keys(obj)) {
1628
+ doWork(key, obj[key]);
1629
+ }
1630
+ for (const value of Object.values(obj)) {
1631
+ doWorkValOnly(value);
1632
+ }
1633
+ for (const [key, value] of Object.entries(obj)) {
1634
+ doWork(key, value);
1635
+ }
1636
+ ```
1637
+
1638
+ #### Grouping parentheses
1639
+
1640
+ Optional grouping parentheses are omitted only when the author and reviewer agree that there is no reasonable chance that the code will be misinterpreted without them, nor would they have made the code easier to read. It is *not* reasonable to assume that every reader has the entire operator precedence table memorized.
1641
+
1642
+ Do not use unnecessary parentheses around the entire expression following `delete` , `typeof` , `void` , `return` , `throw` , `case` , `in` , `of` , or `yield` .
1643
+
1644
+ #### Exception handling
1645
+
1646
+ Exceptions are an important part of the language and should be used whenever exceptional cases occur.
1647
+
1648
+ Custom exceptions provide a great way to convey additional error information from functions. They should be defined and used wherever the native `Error` type is insufficient.
1649
+
1650
+ Prefer throwing exceptions over ad-hoc error-handling approaches (such as passing an error container reference type, or returning an object with an error property).
1651
+
1652
+ ##### Instantiate errors using new
1653
+
1654
+ Always use `new Error()` when instantiating exceptions, instead of just calling `Error()` . Both forms create a new `Error` instance, but using `new` is more consistent with how other objects are instantiated.
1655
+
1656
+ ```
1657
+ throw new Error('Foo is not a valid bar.');
1658
+ ```
1659
+
1660
+ ```
1661
+ throw Error('Foo is not a valid bar.');
1662
+ ```
1663
+
1664
+ ##### Only throw errors
1665
+
1666
+ JavaScript (and thus TypeScript) allow throwing or rejecting a Promise with arbitrary values. However if the thrown or rejected value is not an `Error` , it does not populate stack trace information, making debugging hard. This treatment extends to `Promise` rejection values as `Promise.reject(obj)` is equivalent to `throw obj;` in async functions.
1667
+
1668
+ ```
1669
+ // bad: does not get a stack trace.
1670
+ throw 'oh noes!';
1671
+ // For promises
1672
+ new Promise((resolve, reject) => void reject('oh noes!'));
1673
+ Promise.reject();
1674
+ Promise.reject('oh noes!');
1675
+ ```
1676
+
1677
+ Instead, only throw (subclasses of) `Error` :
1678
+
1679
+ ```
1680
+ // Throw only Errors
1681
+ throw new Error('oh noes!');
1682
+ // ... or subtypes of Error.
1683
+ class MyError extends Error {}
1684
+ throw new MyError('my oh noes!');
1685
+ // For promises
1686
+ new Promise((resolve) => resolve()); // No reject is OK.
1687
+ new Promise((resolve, reject) => void reject(new Error('oh noes!')));
1688
+ Promise.reject(new Error('oh noes!'));
1689
+ ```
1690
+
1691
+ ##### Catching and rethrowing
1692
+
1693
+ When catching errors, code *should* assume that all thrown errors are instances of `Error` .
1694
+
1695
+ ```
1696
+ function assertIsError(e: unknown): asserts e is Error {
1697
+ if (!(e instanceof Error)) throw new Error("e is not an Error");
1698
+ }
1699
+
1700
+ try {
1701
+ doSomething();
1702
+ } catch (e: unknown) {
1703
+ // All thrown errors must be Error subtypes. Do not handle
1704
+ // other possible values unless you know they are thrown.
1705
+ assertIsError(e);
1706
+ displayError(e.message);
1707
+ // or rethrow:
1708
+ throw e;
1709
+ }
1710
+ ```
1711
+
1712
+ Exception handlers *must not* defensively handle non- `Error` types unless the called API is conclusively known to throw non- `Error` s in violation of the above rule. In that case, a comment should be included to specifically identify where the non- `Error` s originate.
1713
+
1714
+ ```
1715
+ try {
1716
+ badApiThrowingStrings();
1717
+ } catch (e: unknown) {
1718
+ // Note: bad API throws strings instead of errors.
1719
+ if (typeof e === 'string') { ... }
1720
+ }
1721
+ ```
1722
+
1723
+ Why?
1724
+
1725
+ Avoid [overly defensive programming](https://en.wikipedia.org/wiki/Defensive_programming#Offensive_programming) . Repeating the same defenses against a problem that will not exist in most code leads to boiler-plate code that is not useful.
1726
+
1727
+ ##### Empty catch blocks
1728
+
1729
+ It is very rarely correct to do nothing in response to a caught exception. When it truly is appropriate to take no action whatsoever in a catch block, the reason this is justified is explained in a comment.
1730
+
1731
+ ```
1732
+ try {
1733
+ return handleNumericResponse(response);
1734
+ } catch (e: unknown) {
1735
+ // Response is not numeric. Continue to handle as text.
1736
+ }
1737
+ return handleTextResponse(response);
1738
+ ```
1739
+
1740
+ Disallowed:
1741
+
1742
+ ```
1743
+ try {
1744
+ shouldFail();
1745
+ fail('expected an error');
1746
+ } catch (expected: unknown) {
1747
+ }
1748
+ ```
1749
+
1750
+ Tip: Unlike in some other languages, patterns like the above simply don't work since this will catch the error thrown by `fail` . Use `assertThrows()` instead.
1751
+
1752
+ #### Switch statements
1753
+
1754
+ All `switch` statements *must* contain a `default` statement group, even if it contains no code. The `default` statement group must be last.
1755
+
1756
+ ```
1757
+ switch (x) {
1758
+ case Y:
1759
+ doSomethingElse();
1760
+ break;
1761
+ default:
1762
+ // nothing to do.
1763
+ }
1764
+ ```
1765
+
1766
+ Within a switch block, each statement group either terminates abruptly with a `break` , a `return` statement, or by throwing an exception. Non-empty statement groups ( `case ...` ) *must not* fall through (enforced by the compiler):
1767
+
1768
+ ```
1769
+ switch (x) {
1770
+ case X:
1771
+ doSomething();
1772
+ // fall through - not allowed!
1773
+ case Y:
1774
+ // ...
1775
+ }
1776
+ ```
1777
+
1778
+ Empty statement groups are allowed to fall through:
1779
+
1780
+ ```
1781
+ switch (x) {
1782
+ case X:
1783
+ case Y:
1784
+ doSomething();
1785
+ break;
1786
+ default: // nothing to do.
1787
+ }
1788
+ ```
1789
+
1790
+ #### Equality checks
1791
+
1792
+ Always use triple equals ( `===` ) and not equals ( `!==` ). The double equality operators cause error prone type coercions that are hard to understand and slower to implement for JavaScript Virtual Machines. See also the [JavaScript equality table](https://dorey.github.io/JavaScript-Equality-Table/) .
1793
+
1794
+ ```
1795
+ if (foo == 'bar' || baz != bam) {
1796
+ // Hard to understand behaviour due to type coercion.
1797
+ }
1798
+ ```
1799
+
1800
+ ```
1801
+ if (foo === 'bar' || baz !== bam) {
1802
+ // All good here.
1803
+ }
1804
+ ```
1805
+
1806
+ **Exception:** Comparisons to the literal `null` value *may* use the `==` and `!=` operators to cover both `null` and `undefined` values.
1807
+
1808
+ ```
1809
+ if (foo == null) {
1810
+ // Will trigger when foo is null or undefined.
1811
+ }
1812
+ ```
1813
+
1814
+ #### Type and non-nullability assertions
1815
+
1816
+ Type assertions ( `x as SomeType` ) and non-nullability assertions ( `y!` ) are unsafe. Both only silence the TypeScript compiler, but do not insert any runtime checks to match these assertions, so they can cause your program to crash at runtime.
1817
+
1818
+ Because of this, you *should not* use type and non-nullability assertions without an obvious or explicit reason for doing so.
1819
+
1820
+ Instead of the following:
1821
+
1822
+ ```
1823
+ (x as Foo).foo();
1824
+
1825
+ y!.bar();
1826
+ ```
1827
+
1828
+ When you want to assert a type or non-nullability the best answer is to explicitly write a runtime check that performs that check.
1829
+
1830
+ ```
1831
+ // assuming Foo is a class.
1832
+ if (x instanceof Foo) {
1833
+ x.foo();
1834
+ }
1835
+
1836
+ if (y) {
1837
+ y.bar();
1838
+ }
1839
+ ```
1840
+
1841
+ Sometimes due to some local property of your code you can be sure that the assertion form is safe. In those situations, you *should* add clarification to explain why you are ok with the unsafe behavior:
1842
+
1843
+ ```
1844
+ // x is a Foo, because ...
1845
+ (x as Foo).foo();
1846
+
1847
+ // y cannot be null, because ...
1848
+ y!.bar();
1849
+ ```
1850
+
1851
+ If the reasoning behind a type or non-nullability assertion is obvious, the comments *may* not be necessary. For example, generated proto code is always nullable, but perhaps it is well-known in the context of the code that certain fields are always provided by the backend. Use your judgement.
1852
+
1853
+ ##### Type assertion syntax
1854
+
1855
+ Type assertions *must* use the `as` syntax (as opposed to the angle brackets syntax). This enforces parentheses around the assertion when accessing a member.
1856
+
1857
+ ```
1858
+ const x = (<Foo>z).length;
1859
+ const y = <Foo>z.length;
1860
+ ```
1861
+
1862
+ ```
1863
+ // z must be Foo because ...
1864
+ const x = (z as Foo).length;
1865
+ ```
1866
+
1867
+ ##### Double assertions
1868
+
1869
+ From the [TypeScript handbook](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions) , TypeScript only allows type assertions which convert to a *more specific* or *less specific* version of a type. Adding a type assertion ( `x as Foo` ) which does not meet this criteria will give the error: Conversion of type 'X' to type 'Y' may be a mistake because neither type sufficiently overlaps with the other.
1870
+
1871
+ If you are sure an assertion is safe, you can perform a *double assertion* . This involves casting through `unknown` since it is less specific than all types.
1872
+
1873
+ ```
1874
+ // x is a Foo here, because...
1875
+ (x as unknown as Foo).fooMethod();
1876
+ ```
1877
+
1878
+ Use `unknown` (instead of `any` or `{}` ) as the intermediate type.
1879
+
1880
+ ##### Type assertions and object literals
1881
+
1882
+ Use type annotations ( `: Foo` ) instead of type assertions ( `as Foo` ) to specify the type of an object literal. This allows detecting refactoring bugs when the fields of an interface change over time.
1883
+
1884
+ ```
1885
+ interface Foo {
1886
+ bar: number;
1887
+ baz?: string; // was "bam", but later renamed to "baz".
1888
+ }
1889
+
1890
+ const foo = {
1891
+ bar: 123,
1892
+ bam: 'abc', // no error!
1893
+ } as Foo;
1894
+
1895
+ function func() {
1896
+ return {
1897
+ bar: 123,
1898
+ bam: 'abc', // no error!
1899
+ } as Foo;
1900
+ }
1901
+ ```
1902
+
1903
+ ```
1904
+ interface Foo {
1905
+ bar: number;
1906
+ baz?: string;
1907
+ }
1908
+
1909
+ const foo: Foo = {
1910
+ bar: 123,
1911
+ bam: 'abc', // complains about "bam" not being defined on Foo.
1912
+ };
1913
+
1914
+ function func(): Foo {
1915
+ return {
1916
+ bar: 123,
1917
+ bam: 'abc', // complains about "bam" not being defined on Foo.
1918
+ };
1919
+ }
1920
+ ```
1921
+
1922
+ #### Keep try blocks focused
1923
+
1924
+ Limit the amount of code inside a try block, if this can be done without hurting readability.
1925
+
1926
+ ```
1927
+ try {
1928
+ const result = methodThatMayThrow();
1929
+ use(result);
1930
+ } catch (error: unknown) {
1931
+ // ...
1932
+ }
1933
+ ```
1934
+
1935
+ ```
1936
+ let result;
1937
+ try {
1938
+ result = methodThatMayThrow();
1939
+ } catch (error: unknown) {
1940
+ // ...
1941
+ }
1942
+ use(result);
1943
+ ```
1944
+
1945
+ Moving the non-throwable lines out of the try/catch block helps the reader learn which method throws exceptions. Some inline calls that do not throw exceptions could stay inside because they might not be worth the extra complication of a temporary variable.
1946
+
1947
+ **Exception:** There may be performance issues if try blocks are inside a loop. Widening try blocks to cover a whole loop is ok.
1948
+
1949
+ ### Decorators
1950
+
1951
+ Decorators are syntax with an `@` prefix, like `@MyDecorator` .
1952
+
1953
+ Do not define new decorators. Only use the decorators defined by frameworks:
1954
+
1955
+ - Angular (e.g. `@Component` , `@NgModule` , etc.)
1956
+ - Polymer (e.g. `@property` )
1957
+
1958
+ Why?
1959
+
1960
+ We generally want to avoid decorators, because they were an experimental feature that have since diverged from the TC39 proposal and have known bugs that won't be fixed.
1961
+
1962
+ When using decorators, the decorator *must* immediately precede the symbol it decorates, with no empty lines between:
1963
+
1964
+ ```
1965
+ /** JSDoc comments go before decorators */
1966
+ @Component({...}) // Note: no empty line after the decorator.
1967
+ class MyComp {
1968
+ @Input() myField: string; // Decorators on fields may be on the same line...
1969
+
1970
+ @Input()
1971
+ myOtherField: string; // ... or wrap.
1972
+ }
1973
+ ```
1974
+
1975
+ ### Disallowed features
1976
+
1977
+ #### Wrapper objects for primitive types
1978
+
1979
+ TypeScript code *must not* instantiate the wrapper classes for the primitive types `String` , `Boolean` , and `Number` . Wrapper classes have surprising behavior, such as `new Boolean(false)` evaluating to `true` .
1980
+
1981
+ ```
1982
+ const s = new String('hello');
1983
+ const b = new Boolean(false);
1984
+ const n = new Number(5);
1985
+ ```
1986
+
1987
+ The wrappers may be called as functions for coercing (which is preferred over using `+` or concatenating the empty string) or creating symbols. See [type coercion](#type-coercion) for more information.
1988
+
1989
+ #### Automatic Semicolon Insertion
1990
+
1991
+ Do not rely on Automatic Semicolon Insertion (ASI). Explicitly end all statements using a semicolon. This prevents bugs due to incorrect semicolon insertions and ensures compatibility with tools with limited ASI support (e.g. clang-format).
1992
+
1993
+ #### Const enums
1994
+
1995
+ Code *must not* use `const enum` ; use plain `enum` instead.
1996
+
1997
+ Why?
1998
+
1999
+ TypeScript enums already cannot be mutated; `const enum` is a separate language feature related to optimization that makes the enum invisible to JavaScript users of the module.
2000
+
2001
+ #### Debugger statements
2002
+
2003
+ Debugger statements *must not* be included in production code.
2004
+
2005
+ ```
2006
+ function debugMe() {
2007
+ debugger;
2008
+ }
2009
+ ```
2010
+
2011
+ #### with
2012
+
2013
+ Do not use the `with` keyword. It makes your code harder to understand and [has been banned in strict mode since ES5](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with) .
2014
+
2015
+ #### Dynamic code evaluation
2016
+
2017
+ Do not use `eval` or the `Function(...string)` constructor (except for code loaders). These features are potentially dangerous and simply do not work in environments using strict [Content Security Policies](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) .
2018
+
2019
+ #### Non-standard features
2020
+
2021
+ Do not use non-standard ECMAScript or Web Platform features.
2022
+
2023
+ This includes:
2024
+
2025
+ - Old features that have been marked deprecated or removed entirely from ECMAScript / the Web Platform (see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features) )
2026
+ - New ECMAScript features that are not yet standardized
2027
+ - Avoid using features that are in current TC39 working draft or currently in the [proposal process](https://tc39.es/process-document/)
2028
+ - Use only ECMAScript features defined in the current ECMA-262 specification
2029
+ - Proposed but not-yet-complete web standards:
2030
+ - WHATWG proposals that have not completed the [proposal process](https://whatwg.org/faq#adding-new-features) .
2031
+ - Non-standard language "extensions" (such as those provided by some external transpilers)
2032
+
2033
+ Projects targeting specific JavaScript runtimes, such as latest-Chrome-only, Chrome extensions, Node.JS, Electron, can obviously use those APIs. Use caution when considering an API surface that is proprietary and only implemented in some browsers; consider whether there is a common library that can abstract this API surface away for you.
2034
+
2035
+ #### Modifying builtin objects
2036
+
2037
+ Never modify builtin types, either by adding methods to their constructors or to their prototypes. Avoid depending on libraries that do this.
2038
+
2039
+ Do not add symbols to the global object unless absolutely necessary (e.g. required by a third-party API).
2040
+
2041
+ ## Naming
2042
+
2043
+ ### Identifiers
2044
+
2045
+ Identifiers *must* use only ASCII letters, digits, underscores (for constants and structured test method names), and (rarely) the '$' sign.
2046
+
2047
+ #### Naming style
2048
+
2049
+ TypeScript expresses information in types, so names *should not* be decorated with information that is included in the type. (See also [Testing Blog](https://testing.googleblog.com/2017/10/code-health-identifiernamingpostforworl.html) for more about what not to include.)
2050
+
2051
+ Some concrete examples of this rule:
2052
+
2053
+ - Do not use trailing or leading underscores for private properties or methods.
2054
+ - Do not use the `opt_` prefix for optional parameters.
2055
+ - For accessors, see [accessor rules](#getters-and-setters-accessors) below.
2056
+ - Do not mark interfaces specially ( ~~`IMyInterface`~~ or ~~`MyFooInterface`~~ ) unless it's idiomatic in its environment. When introducing an interface for a class, give it a name that expresses why the interface exists in the first place (e.g. `class TodoItem` and `interface TodoItemStorage` if the interface expresses the format used for storage/serialization in JSON).
2057
+ - Suffixing `Observable` s with `$` is a common external convention and can help resolve confusion regarding observable values vs concrete values. Judgement on whether this is a useful convention is left up to individual teams, but *should* be consistent within projects.
2058
+
2059
+ #### Descriptive names
2060
+
2061
+ Names *must* be descriptive and clear to a new reader. Do not use abbreviations that are ambiguous or unfamiliar to readers outside your project, and do not abbreviate by deleting letters within a word.
2062
+
2063
+ - **Exception:** Variables that are in scope for 10 lines or fewer, including arguments that are *not* part of an exported API, *may* use short (e.g. single letter) variable names.
2064
+
2065
+ ```
2066
+ // Good identifiers:
2067
+ errorCount // No abbreviation.
2068
+ dnsConnectionIndex // Most people know what "DNS" stands for.
2069
+ referrerUrl // Ditto for "URL".
2070
+ customerId // "Id" is both ubiquitous and unlikely to be misunderstood.
2071
+ ```
2072
+
2073
+ ```
2074
+ // Disallowed identifiers:
2075
+ n // Meaningless.
2076
+ nErr // Ambiguous abbreviation.
2077
+ nCompConns // Ambiguous abbreviation.
2078
+ wgcConnections // Only your group knows what this stands for.
2079
+ pcReader // Lots of things can be abbreviated "pc".
2080
+ cstmrId // Deletes internal letters.
2081
+ kSecondsPerDay // Do not use Hungarian notation.
2082
+ customerID // Incorrect camelcase of "ID".
2083
+ ```
2084
+
2085
+ #### Camel case
2086
+
2087
+ Treat abbreviations like acronyms in names as whole words, i.e. use `loadHttpUrl` , not ~~`loadHTTPURL`~~ , unless required by a platform name (e.g. `XMLHttpRequest` ).
2088
+
2089
+ #### Dollar sign
2090
+
2091
+ Identifiers *should not* generally use `$` , except when required by naming conventions for third party frameworks. [See above](#naming-style) for more on using `$` with `Observable` values.
2092
+
2093
+ ### Rules by identifier type
2094
+
2095
+ Most identifier names should follow the casing in the table below, based on the identifier's type.
2096
+
2097
+ | Style | Category |
2098
+ |------------------|------------------------------------------------------------------------------------------------------------------------|
2099
+ | `UpperCamelCase` | class / interface / type / enum / decorator / type parameters / component functions in TSX / JSXElement type parameter |
2100
+ | `lowerCamelCase` | variable / parameter / function / method / property / module alias |
2101
+ | `CONSTANT_CASE` | global constant values, including enum values. See [Constants](#identifiers-constants) below. |
2102
+ | `#ident` | private identifiers are never used. |
2103
+
2104
+ #### Type parameters
2105
+
2106
+ Type parameters, like in `Array<T>` , *may* use a single upper case character ( `T` ) or `UpperCamelCase` .
2107
+
2108
+ #### Test names
2109
+
2110
+ Test method names inxUnit-style test frameworks *may* be structured with `_` separators, e.g. `testX_whenY_doesZ()` .
2111
+
2112
+ #### \_ prefix/suffix
2113
+
2114
+ Identifiers must not use `_` as a prefix or suffix.
2115
+
2116
+ This also means that `_` *must not* be used as an identifier by itself (e.g. to indicate a parameter is unused).
2117
+
2118
+ Tip: If you only need some of the elements from an array (or TypeScript tuple), you can insert extra commas in a destructuring statement to ignore in-between elements:
2119
+
2120
+ ```
2121
+ const [a, , b] = [1, 5, 10]; // a <- 1, b <- 10
2122
+ ```
2123
+
2124
+ #### Imports
2125
+
2126
+ Module namespace imports are `lowerCamelCase` while files are `snake_case` , which means that imports correctly will not match in casing style, such as
2127
+
2128
+ ```
2129
+ import * as fooBar from './foo_bar';
2130
+ ```
2131
+
2132
+ Some libraries might commonly use a namespace import prefix that violates this naming scheme, but overbearingly common open source use makes the violating style more readable. The only libraries that currently fall under this exception are:
2133
+
2134
+ - [jquery](https://jquery.com/) , using the `$` prefix
2135
+ - [threejs](https://threejs.org/) , using the `THREE` prefix
2136
+
2137
+ #### Constants
2138
+
2139
+ **Immutable** : `CONSTANT_CASE` indicates that a value is *intended* to not be changed, and *may* be used for values that can technically be modified (i.e. values that are not deeply frozen) to indicate to users that they must not be modified.
2140
+
2141
+ ```
2142
+ const UNIT_SUFFIXES = {
2143
+ 'milliseconds': 'ms',
2144
+ 'seconds': 's',
2145
+ };
2146
+ // Even though per the rules of JavaScript UNIT_SUFFIXES is
2147
+ // mutable, the uppercase shows users to not modify it.
2148
+ ```
2149
+
2150
+ A constant can also be a `static readonly` property of a class.
2151
+
2152
+ ```
2153
+ class Foo {
2154
+ private static readonly MY_SPECIAL_NUMBER = 5;
2155
+
2156
+ bar() {
2157
+ return 2 * Foo.MY_SPECIAL_NUMBER;
2158
+ }
2159
+ }
2160
+ ```
2161
+
2162
+ **Global** : Only symbols declared on the module level, static fields of module level classes, and values of module level enums, *may* use `CONST_CASE` . If a value can be instantiated more than once over the lifetime of the program (e.g. a local variable declared within a function, or a static field on a class nested in a function) then it *must* use `lowerCamelCase` .
2163
+
2164
+ If a value is an arrow function that implements an interface, then it *may* be declared `lowerCamelCase` .
2165
+
2166
+ #### Aliases
2167
+
2168
+ When creating a local-scope alias of an existing symbol, use the format of the existing identifier. The local alias *must* match the existing naming and format of the source. For variables use `const` for your local aliases, and for class fields use the `readonly` attribute.
2169
+
2170
+ Note: If you're creating an alias just to expose it to a template in your framework of choice, remember to also apply the proper [access modifiers](#properties-used-outside-of-class-lexical-scope) .
2171
+
2172
+ ```
2173
+ const {BrewStateEnum} = SomeType;
2174
+ const CAPACITY = 5;
2175
+
2176
+ class Teapot {
2177
+ readonly BrewStateEnum = BrewStateEnum;
2178
+ readonly CAPACITY = CAPACITY;
2179
+ }
2180
+ ```
2181
+
2182
+ ## Type system
2183
+
2184
+ ### Type inference
2185
+
2186
+ Code *may* rely on type inference as implemented by the TypeScript compiler for all type expressions (variables, fields, return types, etc).
2187
+
2188
+ ```
2189
+ const x = 15; // Type inferred.
2190
+ ```
2191
+
2192
+ Leave out type annotations for trivially inferred types: variables or parameters initialized to a `string` , `number` , `boolean` , `RegExp` literal or `new` expression.
2193
+
2194
+ ```
2195
+ const x: boolean = true; // Bad: 'boolean' here does not aid readability
2196
+ ```
2197
+
2198
+ ```
2199
+ // Bad: 'Set' is trivially inferred from the initialization
2200
+ const x: Set<string> = new Set();
2201
+ ```
2202
+
2203
+ Explicitly specifying types may be required to prevent generic type parameters from being inferred as `unknown` . For example, initializing generic types with no values (e.g. empty arrays, objects, `Map` s, or `Set` s).
2204
+
2205
+ ```
2206
+ const x = new Set<string>();
2207
+ ```
2208
+
2209
+ For more complex expressions, type annotations can help with readability of the program:
2210
+
2211
+ ```
2212
+ // Hard to reason about the type of 'value' without an annotation.
2213
+ const value = await rpc.getSomeValue().transform();
2214
+ ```
2215
+
2216
+ ```
2217
+ // Can tell the type of 'value' at a glance.
2218
+ const value: string[] = await rpc.getSomeValue().transform();
2219
+ ```
2220
+
2221
+ Whether an annotation is required is decided by the code reviewer.
2222
+
2223
+ #### Return types
2224
+
2225
+ Whether to include return type annotations for functions and methods is up to the code author. Reviewers *may* ask for annotations to clarify complex return types that are hard to understand. Projects *may* have a local policy to always require return types, but this is not a general TypeScript style requirement.
2226
+
2227
+ There are two benefits to explicitly typing out the implicit return values of functions and methods:
2228
+
2229
+ - More precise documentation to benefit readers of the code.
2230
+ - Surface potential type errors faster in the future if there are code changes that change the return type of the function.
2231
+
2232
+ ### Undefined and null
2233
+
2234
+ TypeScript supports `undefined` and `null` types. Nullable types can be constructed as a union type ( `string|null` ); similarly with `undefined` . There is no special syntax for unions of `undefined` and `null` .
2235
+
2236
+ TypeScript code can use either `undefined` or `null` to denote absence of a value, there is no general guidance to prefer one over the other. Many JavaScript APIs use `undefined` (e.g. `Map.get` ), while many DOM and Google APIs use `null` (e.g. `Element.getAttribute` ), so the appropriate absent value depends on the context.
2237
+
2238
+ #### Nullable/undefined type aliases
2239
+
2240
+ Type aliases *must not* include `|null` or `|undefined` in a union type. Nullable aliases typically indicate that null values are being passed around through too many layers of an application, and this clouds the source of the original issue that resulted in `null` . They also make it unclear when specific values on a class or interface might be absent.
2241
+
2242
+ Instead, code *must* only add `|null` or `|undefined` when the alias is actually used. Code *should* deal with null values close to where they arise, using the above techniques.
2243
+
2244
+ ```
2245
+ // Bad
2246
+ type CoffeeResponse = Latte|Americano|undefined;
2247
+
2248
+ class CoffeeService {
2249
+ getLatte(): CoffeeResponse { ... };
2250
+ }
2251
+ ```
2252
+
2253
+ ```
2254
+ // Better
2255
+ type CoffeeResponse = Latte|Americano;
2256
+
2257
+ class CoffeeService {
2258
+ getLatte(): CoffeeResponse|undefined { ... };
2259
+ }
2260
+ ```
2261
+
2262
+ #### Prefer optional over |undefined
2263
+
2264
+ In addition, TypeScript supports a special construct for optional parameters and fields, using `?` :
2265
+
2266
+ ```
2267
+ interface CoffeeOrder {
2268
+ sugarCubes: number;
2269
+ milk?: Whole|LowFat|HalfHalf;
2270
+ }
2271
+
2272
+ function pourCoffee(volume?: Milliliter) { ... }
2273
+ ```
2274
+
2275
+ Optional parameters implicitly include `|undefined` in their type. However, they are different in that they can be left out when constructing a value or calling a method. For example, `{sugarCubes: 1}` is a valid `CoffeeOrder` because `milk` is optional.
2276
+
2277
+ Use optional fields (on interfaces or classes) and parameters rather than a `|undefined` type.
2278
+
2279
+ For classes preferably avoid this pattern altogether and initialize as many fields as possible.
2280
+
2281
+ ```
2282
+ class MyClass {
2283
+ field = '';
2284
+ }
2285
+ ```
2286
+
2287
+ ### Use structural types
2288
+
2289
+ TypeScript's type system is structural, not nominal. That is, a value matches a type if it has at least all the properties the type requires and the properties' types match, recursively.
2290
+
2291
+ When providing a structural-based implementation, explicitly include the type at the declaration of the symbol (this allows more precise type checking and error reporting).
2292
+
2293
+ ```
2294
+ const foo: Foo = {
2295
+ a: 123,
2296
+ b: 'abc',
2297
+ }
2298
+ ```
2299
+
2300
+ ```
2301
+ const badFoo = {
2302
+ a: 123,
2303
+ b: 'abc',
2304
+ }
2305
+ ```
2306
+
2307
+ Use interfaces to define structural types, not classes
2308
+
2309
+ ```
2310
+ interface Foo {
2311
+ a: number;
2312
+ b: string;
2313
+ }
2314
+
2315
+ const foo: Foo = {
2316
+ a: 123,
2317
+ b: 'abc',
2318
+ }
2319
+ ```
2320
+
2321
+ ```
2322
+ class Foo {
2323
+ readonly a: number;
2324
+ readonly b: number;
2325
+ }
2326
+
2327
+ const foo: Foo = {
2328
+ a: 123,
2329
+ b: 'abc',
2330
+ }
2331
+ ```
2332
+
2333
+ Why?
2334
+
2335
+ The badFoo object above relies on type inference. Additional fields could be added to badFoo and the type is inferred based on the object itself.
2336
+
2337
+ When passing a badFoo to a function that takes a Foo , the error will be at the function call site, rather than at the object declaration site. This is also useful when changing the surface of an interface across broad codebases.
2338
+
2339
+ ```
2340
+ interface Animal {
2341
+ sound: string;
2342
+ name: string;
2343
+ }
2344
+
2345
+ function makeSound(animal: Animal) {}
2346
+
2347
+ /**
2348
+ * 'cat' has an inferred type of '{sound: string}'
2349
+ */
2350
+ const cat = {
2351
+ sound: 'meow',
2352
+ };
2353
+
2354
+ /**
2355
+ * 'cat' does not meet the type contract required for the function, so the
2356
+ * TypeScript compiler errors here, which may be very far from where 'cat' is
2357
+ * defined.
2358
+ */
2359
+ makeSound(cat);
2360
+
2361
+ /**
2362
+ * Horse has a structural type and the type error shows here rather than the
2363
+ * function call. 'horse' does not meet the type contract of 'Animal'.
2364
+ */
2365
+ const horse: Animal = {
2366
+ sound: 'niegh',
2367
+ };
2368
+
2369
+ const dog: Animal = {
2370
+ sound: 'bark',
2371
+ name: 'MrPickles',
2372
+ };
2373
+
2374
+ makeSound(dog);
2375
+ makeSound(horse);
2376
+ ```
2377
+
2378
+ ### Prefer interfaces over type literal aliases
2379
+
2380
+ TypeScript supports [type aliases](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-aliases) for naming a type expression. This can be used to name primitives, unions, tuples, and any other types.
2381
+
2382
+ However, when declaring types for objects, use interfaces instead of a type alias for the object literal expression.
2383
+
2384
+ ```
2385
+ interface User {
2386
+ firstName: string;
2387
+ lastName: string;
2388
+ }
2389
+ ```
2390
+
2391
+ ```
2392
+ type User = {
2393
+ firstName: string,
2394
+ lastName: string,
2395
+ }
2396
+ ```
2397
+
2398
+ Why?
2399
+
2400
+ These forms are nearly equivalent, so under the principle of just choosing one out of two forms to prevent variation, we should choose one. Additionally, there are also [interesting technical reasons to prefer interface](https://ncjamieson.com/prefer-interfaces/) . That page quotes the TypeScript team lead: Honestly, my take is that it should really just be interfaces for anything that they can model. There is no benefit to type aliases when there are so many issues around display/perf.
2401
+
2402
+ ### Array&lt;T&gt; Type
2403
+
2404
+ For simple types (containing just alphanumeric characters and dot), use the syntax sugar for arrays, `T[]` or `readonly T[]` , rather than the longer form `Array<T>` or `ReadonlyArray<T>` .
2405
+
2406
+ For multi-dimensional non- `readonly` arrays of simple types, use the syntax sugar form ( `T[][]` , `T[][][]` , and so on) rather than the longer form.
2407
+
2408
+ For anything more complex, use the longer form `Array<T>` .
2409
+
2410
+ These rules apply at each level of nesting, i.e. a simple `T[]` nested in a more complex type would still be spelled as `T[]` , using the syntax sugar.
2411
+
2412
+ ```
2413
+ let a: string[];
2414
+ let b: readonly string[];
2415
+ let c: ns.MyObj[];
2416
+ let d: string[][];
2417
+ let e: Array<{n: number, s: string}>;
2418
+ let f: Array<string|number>;
2419
+ let g: ReadonlyArray<string|number>;
2420
+ let h: InjectionToken<string[]>; // Use syntax sugar for nested types.
2421
+ let i: ReadonlyArray<string[]>;
2422
+ let j: Array<readonly string[]>;
2423
+ ```
2424
+
2425
+ ```
2426
+ let a: Array<string>; // The syntax sugar is shorter.
2427
+ let b: ReadonlyArray<string>;
2428
+ let c: Array<ns.MyObj>;
2429
+ let d: Array<string[]>;
2430
+ let e: {n: number, s: string}[]; // The braces make it harder to read.
2431
+ let f: (string|number)[]; // Likewise with parens.
2432
+ let g: readonly (string | number)[];
2433
+ let h: InjectionToken<Array<string>>;
2434
+ let i: readonly string[][];
2435
+ let j: (readonly string[])[];
2436
+ ```
2437
+
2438
+ ### Indexable types / index signatures ( {[key: string]: T} )
2439
+
2440
+ In JavaScript, it's common to use an object as an associative array (aka map , hash , or dict ). Such objects can be typed using an [index signature](https://www.typescriptlang.org/docs/handbook/2/objects.html#index-signatures) ( `[k: string]: T` ) in TypeScript:
2441
+
2442
+ ```
2443
+ const fileSizes: {[fileName: string]: number} = {};
2444
+ fileSizes['readme.txt'] = 541;
2445
+ ```
2446
+
2447
+ In TypeScript, provide a meaningful label for the key. (The label only exists for documentation; it's unused otherwise.)
2448
+
2449
+ ```
2450
+ const users: {[key: string]: number} = ...;
2451
+ ```
2452
+
2453
+ ```
2454
+ const users: {[userName: string]: number} = ...;
2455
+ ```
2456
+
2457
+ Rather than using one of these, consider using the ES6 `Map` and `Set` types instead. JavaScript objects have [surprising undesirable behaviors](http://2ality.com/2012/01/objects-as-maps.html) and the ES6 types more explicitly convey your intent. Also, `Map` s can be keyed by-and `Set` s can contain-types other than `string` .
2458
+
2459
+ TypeScript's builtin `Record<Keys, ValueType>` type allows constructing types with a defined set of keys. This is distinct from associative arrays in that the keys are statically known. See advice on that [below](#mapped-conditional-types) .
2460
+
2461
+ ### Mapped and conditional types
2462
+
2463
+ TypeScript's [mapped types](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html) and [conditional types](https://www.typescriptlang.org/docs/handbook/2/conditional-types.html) allow specifying new types based on other types. TypeScript's standard library includes several type operators based on these ( `Record` , `Partial` , `Readonly` etc).
2464
+
2465
+ These type system features allow succinctly specifying types and constructing powerful yet type safe abstractions. They come with a number of drawbacks though:
2466
+
2467
+ - Compared to explicitly specifying properties and type relations (e.g. using interfaces and extension, see below for an example), type operators require the reader to mentally evaluate the type expression. This can make programs substantially harder to read, in particular combined with type inference and expressions crossing file boundaries.
2468
+ - Mapped &amp; conditional types' evaluation model, in particular when combined with type inference, is underspecified, not always well understood, and often subject to change in TypeScript compiler versions. Code can accidentally compile or seem to give the right results. This increases future support cost of code using type operators.
2469
+ - Mapped &amp; conditional types are most powerful when deriving types from complex and/or inferred types. On the flip side, this is also when they are most prone to create hard to understand and maintain programs.
2470
+ - Some language tooling does not work well with these type system features. E.g. your IDE's find references (and thus rename property refactoring) will not find properties in a `Pick<T, Keys>` type, and Code Search won't hyperlink them.
2471
+
2472
+ The style recommendation is:
2473
+
2474
+ - Always use the simplest type construct that can possibly express your code.
2475
+ - A little bit of repetition or verbosity is often much cheaper than the long term cost of complex type expressions.
2476
+ - Mapped &amp; conditional types may be used, subject to these considerations.
2477
+
2478
+ For example, TypeScript's builtin `Pick<T, Keys>` type allows creating a new type by subsetting another type `T` , but simple interface extension can often be easier to understand.
2479
+
2480
+ ```
2481
+ interface User {
2482
+ shoeSize: number;
2483
+ favoriteIcecream: string;
2484
+ favoriteChocolate: string;
2485
+ }
2486
+
2487
+ // FoodPreferences has favoriteIcecream and favoriteChocolate, but not shoeSize.
2488
+ type FoodPreferences = Pick<User, 'favoriteIcecream'|'favoriteChocolate'>;
2489
+ ```
2490
+
2491
+ This is equivalent to spelling out the properties on `FoodPreferences` :
2492
+
2493
+ ```
2494
+ interface FoodPreferences {
2495
+ favoriteIcecream: string;
2496
+ favoriteChocolate: string;
2497
+ }
2498
+ ```
2499
+
2500
+ To reduce duplication, `User` could extend `FoodPreferences` , or (possibly better) nest a field for food preferences:
2501
+
2502
+ ```
2503
+ interface FoodPreferences { /* as above */ }
2504
+ interface User extends FoodPreferences {
2505
+ shoeSize: number;
2506
+ // also includes the preferences.
2507
+ }
2508
+ ```
2509
+
2510
+ Using interfaces here makes the grouping of properties explicit, improves IDE support, allows better optimization, and arguably makes the code easier to understand.
2511
+
2512
+ ### any Type
2513
+
2514
+ TypeScript's `any` type is a super and subtype of all other types, and allows dereferencing all properties. As such, `any` is dangerous - it can mask severe programming errors, and its use undermines the value of having static types in the first place.
2515
+
2516
+ **Consider** ***not*** **to use** **`any`** **.** In circumstances where you want to use `any` , consider one of:
2517
+
2518
+ - [Provide a more specific type](#any-specific)
2519
+ - [Use](#any-unknown) [`unknown`](#any-unknown)
2520
+ - [Suppress the lint warning and document why](#any-suppress)
2521
+
2522
+ #### Providing a more specific type
2523
+
2524
+ Use interfaces , an inline object type, or a type alias:
2525
+
2526
+ ```
2527
+ // Use declared interfaces to represent server-side JSON.
2528
+ declare interface MyUserJson {
2529
+ name: string;
2530
+ email: string;
2531
+ }
2532
+
2533
+ // Use type aliases for types that are repetitive to write.
2534
+ type MyType = number|string;
2535
+
2536
+ // Or use inline object types for complex returns.
2537
+ function getTwoThings(): {something: number, other: string} {
2538
+ // ...
2539
+ return {something, other};
2540
+ }
2541
+
2542
+ // Use a generic type, where otherwise a library would say `any` to represent
2543
+ // they don't care what type the user is operating on (but note "Return type
2544
+ // only generics" below).
2545
+ function nicestElement<T>(items: T[]): T {
2546
+ // Find the nicest element in items.
2547
+ // Code can also put constraints on T, e.g. <T extends HTMLElement>.
2548
+ }
2549
+ ```
2550
+
2551
+ #### Using unknown over any
2552
+
2553
+ The `any` type allows assignment into any other type and dereferencing any property off it. Often this behaviour is not necessary or desirable, and code just needs to express that a type is unknown. Use the built-in type `unknown` in that situation - it expresses the concept and is much safer as it does not allow dereferencing arbitrary properties.
2554
+
2555
+ ```
2556
+ // Can assign any value (including null or undefined) into this but cannot
2557
+ // use it without narrowing the type or casting.
2558
+ const val: unknown = value;
2559
+ ```
2560
+
2561
+ ```
2562
+ const danger: any = value /* result of an arbitrary expression */;
2563
+ danger.whoops(); // This access is completely unchecked!
2564
+ ```
2565
+
2566
+ To safely use `unknown` values, narrow the type using a [type guard](https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types)
2567
+
2568
+ #### Suppressing any lint warnings
2569
+
2570
+ Sometimes using `any` is legitimate, for example in tests to construct a mock object. In such cases, add a comment that suppresses the lint warning, and document why it is legitimate.
2571
+
2572
+ ```
2573
+ // This test only needs a partial implementation of BookService, and if
2574
+ // we overlooked something the test will fail in an obvious way.
2575
+ // This is an intentionally unsafe partial mock
2576
+ // tslint:disable-next-line:no-any
2577
+ const mockBookService = ({get() { return mockBook; }} as any) as BookService;
2578
+ // Shopping cart is not used in this test
2579
+ // tslint:disable-next-line:no-any
2580
+ const component = new MyComponent(mockBookService, /* unused ShoppingCart */ null as any);
2581
+ ```
2582
+
2583
+ ### {} Type
2584
+
2585
+ The `{}` type, also known as an *empty interface* type, represents a interface with no properties. An empty interface type has no specified properties and therefore any non-nullish value is assignable to it.
2586
+
2587
+ ```
2588
+ let player: {};
2589
+
2590
+ player = {
2591
+ health: 50,
2592
+ }; // Allowed.
2593
+
2594
+ console.log(player.health) // Property 'health' does not exist on type '{}'.
2595
+ ```
2596
+
2597
+ ```
2598
+ function takeAnything(obj:{}) {
2599
+
2600
+ }
2601
+
2602
+ takeAnything({});
2603
+ takeAnything({ a: 1, b: 2 });
2604
+ ```
2605
+
2606
+ Google3 code **should not** use `{}` for most use cases. `{}` represents any non-nullish primitive or object type, which is rarely appropriate. Prefer one of the following more-descriptive types:
2607
+
2608
+ - `unknown` can hold any value, including `null` or `undefined` , and is generally more appropriate for opaque values.
2609
+ - `Record<string, T>` is better for dictionary-like objects, and provides better type safety by being explicit about the type `T` of contained values (which may itself be `unknown` ).
2610
+ - `object` excludes primitives as well, leaving only non-nullish functions and objects, but without any other assumptions about what properties may be available.
2611
+
2612
+ ### Tuple types
2613
+
2614
+ If you are tempted to create a Pair type, instead use a tuple type:
2615
+
2616
+ ```
2617
+ interface Pair {
2618
+ first: string;
2619
+ second: string;
2620
+ }
2621
+ function splitInHalf(input: string): Pair {
2622
+ ...
2623
+ return {first: x, second: y};
2624
+ }
2625
+ ```
2626
+
2627
+ ```
2628
+ function splitInHalf(input: string): [string, string] {
2629
+ ...
2630
+ return [x, y];
2631
+ }
2632
+
2633
+ // Use it like:
2634
+ const [leftHalf, rightHalf] = splitInHalf('my string');
2635
+ ```
2636
+
2637
+ However, often it's clearer to provide meaningful names for the properties.
2638
+
2639
+ If declaring an `interface` is too heavyweight, you can use an inline object literal type:
2640
+
2641
+ ```
2642
+ function splitHostPort(address: string): {host: string, port: number} {
2643
+ ...
2644
+ }
2645
+
2646
+ // Use it like:
2647
+ const address = splitHostPort(userAddress);
2648
+ use(address.port);
2649
+
2650
+ // You can also get tuple-like behavior using destructuring:
2651
+ const {host, port} = splitHostPort(userAddress);
2652
+ ```
2653
+
2654
+ ### Wrapper types
2655
+
2656
+ There are a few types related to JavaScript primitives that *should not* ever be used:
2657
+
2658
+ - `String` , `Boolean` , and `Number` have slightly different meaning from the corresponding primitive types `string` , `boolean` , and `number` . Always use the lowercase version.
2659
+ - `Object` has similarities to both `{}` and `object` , but is slightly looser. Use `{}` for a type that include everything except `null` and `undefined` , or lowercase `object` to further exclude the other primitive types (the three mentioned above, plus `symbol` and `bigint` ).
2660
+
2661
+ Further, never invoke the wrapper types as constructors (with `new` ).
2662
+
2663
+ ### Return type only generics
2664
+
2665
+ Avoid creating APIs that have return type only generics. When working with existing APIs that have return type only generics always explicitly specify the generics.
2666
+
2667
+ ## Toolchain requirements
2668
+
2669
+ Google style requires using a number of tools in specific ways, outlined here.
2670
+
2671
+ ### TypeScript compiler
2672
+
2673
+ All TypeScript files must pass type checking using the standard tool chain.
2674
+
2675
+ #### @ts-ignore
2676
+
2677
+ Do not use `@ts-ignore` nor the variants `@ts-expect-error` or `@ts-nocheck` .
2678
+
2679
+ Why?
2680
+
2681
+ They superficially seem to be an easy way to fix a compiler error, but in practice, a specific compiler error is often caused by a larger problem that can be fixed more directly.
2682
+
2683
+ For example, if you are using `@ts-ignore` to suppress a type error, then it's hard to predict what types the surrounding code will end up seeing. For many type errors, the advice in [how to best use](#any) [`any`](#any) is useful.
2684
+
2685
+ You may use `@ts-expect-error` in unit tests, though you generally *should not* . `@ts-expect-error` suppresses all errors. It's easy to accidentally over-match and suppress more serious errors. Consider one of:
2686
+
2687
+ - When testing APIs that need to deal with unchecked values at runtime, add casts to the expected type or to `any` and add an explanatory comment. This limits error suppression to a single expression.
2688
+ - Suppress the lint warning and document why, similar to [suppressing](#any-suppress) [`any`](#any-suppress) [lint warnings](#any-suppress) .
2689
+
2690
+ ### Conformance
2691
+
2692
+ Google TypeScript includes several *conformance frameworks* , [tsetse](https://tsetse.info/) and [tsec](https://github.com/google/tsec) .
2693
+
2694
+ These rules are commonly used to enforce critical restrictions (such as defining globals, which could break the codebase) and security patterns (such as using `eval` or assigning to `innerHTML` ), or more loosely to improve code quality.
2695
+
2696
+ Google-style TypeScript must abide by any applicable global or framework-local conformance rules.
2697
+
2698
+ ## Comments and documentation
2699
+
2700
+ #### JSDoc versus comments
2701
+
2702
+ There are two types of comments, JSDoc ( `/** ... */` ) and non-JSDoc ordinary comments ( `// ...` or `/* ... */` ).
2703
+
2704
+ - Use `/** JSDoc */` comments for documentation, i.e. comments a user of the code should read.
2705
+ - Use `// line comments` for implementation comments, i.e. comments that only concern the implementation of the code itself.
2706
+
2707
+ JSDoc comments are understood by tools (such as editors and documentation generators), while ordinary comments are only for other humans.
2708
+
2709
+ #### Multi-line comments
2710
+
2711
+ Multi-line comments are indented at the same level as the surrounding code. They *must* use multiple single-line comments ( `//` -style), not block comment style ( `/* */` ).
2712
+
2713
+ ```
2714
+ // This is
2715
+ // fine
2716
+ ```
2717
+
2718
+ ```
2719
+ /*
2720
+ * This should
2721
+ * use multiple
2722
+ * single-line comments
2723
+ */
2724
+
2725
+ /* This should use // */
2726
+ ```
2727
+
2728
+ Comments are not enclosed in boxes drawn with asterisks or other characters.
2729
+
2730
+ ### JSDoc general form
2731
+
2732
+ The basic formatting of JSDoc comments is as seen in this example:
2733
+
2734
+ ```
2735
+ /**
2736
+ * Multiple lines of JSDoc text are written here,
2737
+ * wrapped normally.
2738
+ * @param arg A number to do something to.
2739
+ */
2740
+ function doSomething(arg: number) { ... }
2741
+ ```
2742
+
2743
+ or in this single-line example:
2744
+
2745
+ ```
2746
+ /** This short jsdoc describes the function. */
2747
+ function doSomething(arg: number) { ... }
2748
+ ```
2749
+
2750
+ If a single-line comment overflows into multiple lines, it *must* use the multi-line style with `/**` and `*/` on their own lines.
2751
+
2752
+ Many tools extract metadata from JSDoc comments to perform code validation and optimization. As such, these comments *must* be well-formed.
2753
+
2754
+ ### Markdown
2755
+
2756
+ JSDoc is written in Markdown, though it *may* include HTML when necessary.
2757
+
2758
+ This means that tooling parsing JSDoc will ignore plain text formatting, so if you did this:
2759
+
2760
+ ```
2761
+ /**
2762
+ * Computes weight based on three factors:
2763
+ * items sent
2764
+ * items received
2765
+ * last timestamp
2766
+ */
2767
+ ```
2768
+
2769
+ it will be rendered like this:
2770
+
2771
+ ```
2772
+ Computes weight based on three factors: items sent items received last timestamp
2773
+ ```
2774
+
2775
+ Instead, write a Markdown list:
2776
+
2777
+ ```
2778
+ /**
2779
+ * Computes weight based on three factors:
2780
+ *
2781
+ * - items sent
2782
+ * - items received
2783
+ * - last timestamp
2784
+ */
2785
+ ```
2786
+
2787
+ ### JSDoc tags
2788
+
2789
+ Google style allows a subset of JSDoc tags. Most tags must occupy their own line, with the tag at the beginning of the line.
2790
+
2791
+ ```
2792
+ /**
2793
+ * The "param" tag must occupy its own line and may not be combined.
2794
+ * @param left A description of the left param.
2795
+ * @param right A description of the right param.
2796
+ */
2797
+ function add(left: number, right: number) { ... }
2798
+ ```
2799
+
2800
+ ```
2801
+ /**
2802
+ * The "param" tag must occupy its own line and may not be combined.
2803
+ * @param left @param right
2804
+ */
2805
+ function add(left: number, right: number) { ... }
2806
+ ```
2807
+
2808
+ ### Line wrapping
2809
+
2810
+ Line-wrapped block tags are indented four spaces. Wrapped description text *may* be lined up with the description on previous lines, but this horizontal alignment is discouraged.
2811
+
2812
+ ```
2813
+ /**
2814
+ * Illustrates line wrapping for long param/return descriptions.
2815
+ * @param foo This is a param with a particularly long description that just
2816
+ * doesn't fit on one line.
2817
+ * @return This returns something that has a lengthy description too long to fit
2818
+ * in one line.
2819
+ */
2820
+ exports.method = function(foo) {
2821
+ return 5;
2822
+ };
2823
+ ```
2824
+
2825
+ Do not indent when wrapping a `@desc` or `@fileoverview` description.
2826
+
2827
+ ### Document all top-level exports of modules
2828
+
2829
+ Use `/** JSDoc */` comments to communicate information to the users of your code. Avoid merely restating the property or parameter name. You *should* also document all properties and methods (exported/public or not) whose purpose is not immediately obvious from their name, as judged by your reviewer.
2830
+
2831
+ **Exception:** Symbols that are only exported to be consumed by tooling, such as @NgModule classes, do not require comments.
2832
+
2833
+ ### Class comments
2834
+
2835
+ JSDoc comments for classes should provide the reader with enough information to know how and when to use the class, as well as any additional considerations necessary to correctly use the class. Textual descriptions may be omitted on the constructor.
2836
+
2837
+ ### Method and function comments
2838
+
2839
+ Method, parameter, and return descriptions may be omitted if they are obvious from the rest of the method's JSDoc or from the method name and type signature.
2840
+
2841
+ Method descriptions begin with a verb phrase that describes what the method does. This phrase is not an imperative sentence, but instead is written in the third person, as if there is an implied This method ... before it.
2842
+
2843
+ ### Parameter property comments
2844
+
2845
+ A [parameter property](https://www.typescriptlang.org/docs/handbook/2/classes.html#parameter-properties) is a constructor parameter that is prefixed by one of the modifiers `private` , `protected` , `public` , or `readonly` . A parameter property declares both a parameter and an instance property, and implicitly assigns into it. For example, `constructor(private readonly foo: Foo)` , declares that the constructor takes a parameter `foo` , but also declares a private readonly property `foo` , and assigns the parameter into that property before executing the remainder of the constructor.
2846
+
2847
+ To document these fields, use JSDoc's `@param` annotation. Editors display the description on constructor calls and property accesses.
2848
+
2849
+ ```
2850
+ /** This class demonstrates how parameter properties are documented. */
2851
+ class ParamProps {
2852
+ /**
2853
+ * @param percolator The percolator used for brewing.
2854
+ * @param beans The beans to brew.
2855
+ */
2856
+ constructor(
2857
+ private readonly percolator: Percolator,
2858
+ private readonly beans: CoffeeBean[]) {}
2859
+ }
2860
+ ```
2861
+
2862
+ ```
2863
+ /** This class demonstrates how ordinary fields are documented. */
2864
+ class OrdinaryClass {
2865
+ /** The bean that will be used in the next call to brew(). */
2866
+ nextBean: CoffeeBean;
2867
+
2868
+ constructor(initialBean: CoffeeBean) {
2869
+ this.nextBean = initialBean;
2870
+ }
2871
+ }
2872
+ ```
2873
+
2874
+ ### JSDoc type annotations
2875
+
2876
+ JSDoc type annotations are redundant in TypeScript source code. Do not declare types in `@param` or `@return` blocks, do not write `@implements` , `@enum` , `@private` , `@override` etc. on code that uses the `implements` , `enum` , `private` , `override` etc. keywords.
2877
+
2878
+ ### Make comments that actually add information
2879
+
2880
+ For non-exported symbols, sometimes the name and type of the function or parameter is enough. Code will *usually* benefit from more documentation than just variable names though!
2881
+
2882
+ - Avoid comments that just restate the parameter name and type, e.g. `/** @param fooBarService The Bar service for the Foo application. */`
2883
+ - Because of this rule, `@param` and `@return` lines are only required when they add information, and *may* otherwise be omitted. `/** * POSTs the request to start coffee brewing. * @param amountLitres The amount to brew. Must fit the pot size! */ brew(amountLitres: number, logger: Logger) { // ... }`
2884
+
2885
+ #### Comments when calling a function
2886
+
2887
+ "Parameter name" comments should be used whenever the method name and parameter value do not sufficiently convey the meaning of the parameter.
2888
+
2889
+ Before adding these comments, consider refactoring the method to instead accept an interface and destructure it to greatly improve call-site readability.
2890
+
2891
+ Parameter name comments go before the parameter value, and include the parameter name and a `=` suffix:
2892
+
2893
+ ```
2894
+ someFunction(obviousParam, /* shouldRender= */ true, /* name= */ 'hello');
2895
+ ```
2896
+
2897
+ Existing code may use a legacy parameter name comment style, which places these comments ~after~ the parameter value and omits the `=` . Continuing to use this style within the file for consistency is acceptable.
2898
+
2899
+ ```
2900
+ someFunction(obviousParam, true /* shouldRender */, 'hello' /* name */);
2901
+ ```
2902
+
2903
+ ### Place documentation prior to decorators
2904
+
2905
+ When a class, method, or property have both decorators like `@Component` and JsDoc, please make sure to write the JsDoc before the decorator.
2906
+
2907
+ - Do not write JsDoc between the Decorator and the decorated statement. `@Component({ selector: 'foo', template: 'bar', }) /** Component that prints "bar". */ export class FooComponent {}`
2908
+ - Write the JsDoc block before the Decorator. `/** Component that prints "bar". */ @Component({ selector: 'foo', template: 'bar', }) export class FooComponent {}`
2909
+
2910
+ ## Policies
2911
+
2912
+ ### Consistency
2913
+
2914
+ For any style question that isn't settled definitively by this specification, do what the other code in the same file is already doing ( be consistent ). If that doesn't resolve the question, consider emulating the other files in the same directory.
2915
+
2916
+ Brand new files *must* use Google Style, regardless of the style choices of other files in the same package. When adding new code to a file that is not in Google Style, reformatting the existing code first is recommended, subject to the advice [below](#reformatting-existing-code) . If this reformatting is not done, then new code *should* be as consistent as possible with existing code in the same file, but *must not* violate the style guide.
2917
+
2918
+ #### Reformatting existing code
2919
+
2920
+ You will occasionally encounter files in the codebase that are not in proper Google Style. These may have come from an acquisition, or may have been written before Google Style took a position on some issue, or may be in non-Google Style for any other reason.
2921
+
2922
+ When updating the style of existing code, follow these guidelines.
2923
+
2924
+ 1. It is not required to change all existing code to meet current style guidelines. Reformatting existing code is a trade-off between code churn and consistency. Style rules evolve over time and these kinds of tweaks to maintain compliance would create unnecessary churn. However, if significant changes are being made to a file it is expected that the file will be in Google Style.
2925
+ 2. Be careful not to allow opportunistic style fixes to muddle the focus of a CL. If you find yourself making a lot of style changes that aren't critical to the central focus of a CL, promote those changes to a separate CL.
2926
+
2927
+ ### Deprecation
2928
+
2929
+ Mark deprecated methods, classes or interfaces with an `@deprecated` JSDoc annotation. A deprecation comment must include simple, clear directions for people to fix their call sites.
2930
+
2931
+ ### Generated code: mostly exempt
2932
+
2933
+ Source code generated by the build process is not required to be in Google Style. However, any generated identifiers that will be referenced from hand-written source code must follow the naming requirements. As a special exception, such identifiers are allowed to contain underscores, which may help to avoid conflicts with hand-written identifiers.
2934
+
2935
+ #### Style guide goals
2936
+
2937
+ In general, engineers usually know best about what's needed in their code, so if there are multiple options and the choice is situation dependent, we should let decisions be made locally. So the default answer should be leave it out .
2938
+
2939
+ The following points are the exceptions, which are the reasons we have some global rules. Evaluate your style guide proposal against the following:
2940
+
2941
+ 1. **Code should avoid patterns that are known to cause problems, especially for users new to the language.**
2942
+ 2. **Code across projects should be consistent across irrelevant variations.** When there are two options that are equivalent in a superficial way, we should consider choosing one just so we don't divergently evolve for no reason and avoid pointless debates in code reviews. Examples:
2943
+ - The capitalization style of names.
2944
+ - `x as T` syntax vs the equivalent `<T>x` syntax (disallowed).
2945
+ - `Array<[number, number]>` vs `[number, number][]` .
2946
+ 3. **Code should be maintainable in the long term.** Code usually lives longer than the original author works on it, and the TypeScript team must keep all of Google working into the future. Examples:
2947
+ - We use software to automate changes to code, so code is autoformatted so it's easy for software to meet whitespace rules.
2948
+ - We require a single set of compiler flags, so a given TS library can be written assuming a specific set of flags, and users can always safely use a shared library.
2949
+ - Code must import the libraries it uses ( strict deps ) so that a refactor in a dependency doesn't change the dependencies of its users.
2950
+ - We ask users to write tests. Without tests we cannot have confidence that changes that we make to the language, don't break users.
2951
+ 4. **Code reviewers should be focused on improving the quality of the code, not enforcing arbitrary rules.** If it's possible to implement your rule as an automated check that is often a good sign. This also supports principle 3. If it really just doesn't matter that much -- if it's an obscure corner of the language or if it avoids a bug that is unlikely to occur -- it's probably worth leaving out.
2952
+
2953
+ 1. Namespace imports are often called 'module imports' [↩](#fnref1)
2954
+ 2. named imports are sometimes called 'destructuring imports' because they use similar syntax to destructuring assignments.