forked from google/styleguide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tsguide.html
2437 lines (1875 loc) · 85 KB
/
tsguide.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Google TypeScript Style Guide</title>
<link rel="stylesheet" href="javaguide.css">
<script src="include/styleguide.js"></script>
<link rel="shortcut icon" href="https://www.google.com/favicon.ico">
<script src="include/jsguide.js"></script>
</head>
<body onload="initStyleGuide();">
<div id="content">
<h1>Google TypeScript Style Guide</h1>
<h1>TypeScript style guide</h1>
<section>
This is the external guide that's based on the internal Google version but has been adjusted for the broader audience. There is no automatic deployment process for this version as it's pushed on-demand by volunteers.
<p>It contains both rules and best practices. Choose those that work best for your team.
</p></section>
<p>This Style Guide uses <a href="http://tools.ietf.org/html/rfc2119">RFC 2119</a> terminology
when using the phrases <em>must</em>, <em>must not</em>, <em>should</em>, <em>should not</em>, and <em>may</em>.
All examples given are non-normative and serve only to illustrate the normative
language of the style guide.</p>
<h2 id="syntax">Syntax</h2>
<h3 id="identifiers">Identifiers</h3>
<p>Identifiers must use only ASCII letters, digits, underscores (for constants and
structured test method names), and the '\(' sign. Thus each valid identifier name
is matched by the regular expression `[\)\w]+`.</p>
<table>
<thead>
<tr>
<th>Style</th>
<th>Category</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>UpperCamelCase</code>
</td>
<td>class / interface / type / enum / decorator / type
parameters</td>
</tr>
<tr>
<td><code>lowerCamelCase</code>
</td>
<td>variable / parameter / function / method / property /
module alias</td>
</tr>
<tr>
<td><code>CONSTANT_CASE</code></td>
<td>global constant values, including enum values</td>
</tr>
<tr>
<td><code>#ident</code></td>
<td>private identifiers are never used.</td>
</tr>
</tbody>
</table>
<ul>
<li><p><strong>Abbreviations</strong>:
Treat abbreviations like acronyms in names as whole words, i.e. use
<code>loadHttpUrl</code>, not <del><code>loadHTTPURL</code></del>, unless required by a platform name
(e.g. <code>XMLHttpRequest</code>).</p></li>
<li><p><strong>Dollar sign</strong>: Identifiers <em>should not</em> generally use <code>$</code>, except when
aligning with naming conventions for third party frameworks.
<a href="#naming-style">See below</a> for more on using <code>$</code> with <code>Observable</code> values.</p></li>
<li><p><strong>Type parameters</strong>: Type parameters, like in <code>Array<T></code>, may use a single
upper case character (<code>T</code>) or <code>UpperCamelCase</code>.</p></li>
<li><p><strong>Test names</strong>: Test method names in Closure <code>testSuite</code>s and similar
xUnit-style test frameworks may be structured with <code>_</code> separators, e.g.
<code>testX_whenY_doesZ()</code>.</p></li>
<li><p><strong><code>_</code> prefix/suffix</strong>: Identifiers must not use <code>_</code> as a prefix or suffix.</p>
<p>This also means that <code>_</code> must not be used as an identifier by itself (e.g.
to indicate a parameter is unused).</p></li>
</ul>
<blockquote>
<p>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:</p>
<pre><code class="language-ts">const [a, , b] = [1, 5, 10]; // a <- 1, b <- 10
</code></pre>
</blockquote>
<ul>
<li><p><strong>Imports</strong>: Module namespace imports are <code>lowerCamelCase</code> while files are
<code>snake_case</code>, which means that imports correctly will not match in casing
style, such as</p>
<pre><code class="language-ts good">import * as fooBar from './foo_bar';
</code></pre>
<p>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:</p>
<ul>
<li><a href="https://jquery.com/">jquery</a>, using the <code>$</code> prefix</li>
<li><a href="https://threejs.org/">threejs</a>, using the <code>THREE</code> prefix</li>
</ul></li>
<li><p><strong>Constants</strong>: <code>CONSTANT_CASE</code> indicates that a value is <em>intended</em> 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.</p>
<pre><code class="language-ts good">const UNIT_SUFFIXES = {
'milliseconds': 'ms',
'seconds': 's',
};
// Even though per the rules of JavaScript UNIT_SUFFIXES is
// mutable, the uppercase shows users to not modify it.
</code></pre>
<p>A constant can also be a <code>static readonly</code> property of a class.</p>
<pre><code class="language-ts good">class Foo {
private static readonly MY_SPECIAL_NUMBER = 5;
bar() {
return 2 * Foo.MY_SPECIAL_NUMBER;
}
}
</code></pre>
<p>If a value can be instantiated more than once over the lifetime of the
program, or if users mutate it in any way, it must use <code>lowerCamelCase</code>.</p>
<p>If a value is an arrow function that implements an interface, then it can be
declared <code>lowerCamelCase</code>.</p></li>
<li>
</li>
</ul>
<h4 id="aliases">Aliases</h4>
<p>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 <code>const</code> for your local aliases, and for class
fields use the <code>readonly</code> attribute.</p>
<pre><code class="language-ts good">
const {Foo} = SomeType;
const CAPACITY = 5;
class Teapot {
readonly BrewStateEnum = BrewStateEnum;
readonly CAPACITY = CAPACITY;
}
</code></pre>
<h4 id="naming-style">Naming style</h4>
<p>TypeScript expresses information in types, so names <em>should not</em> be decorated
with information that is included in the type. (See also
<a href="https://testing.googleblog.com/2017/10/code-health-identifiernamingpostforworl.html">Testing Blog</a>
for more about what
not to include.)</p>
<p>Some concrete examples of this rule:</p>
<ul>
<li>Do not use trailing or leading underscores for private properties or
methods.</li>
<li>Do not use the <code>opt_</code> prefix for optional parameters.
<ul>
<li>For accessors, see <a href="#getters-and-setters-accessors">accessor rules</a>
below.</li>
</ul></li>
<li>Do not mark interfaces specially (<del><code>IMyInterface</code></del> or
<del><code>MyFooInterface</code></del>) 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. <code>class TodoItem</code> and <code>interface
TodoItemStorage</code> if the interface expresses the format used for
storage/serialization in JSON).</li>
<li>Suffixing <code>Observable</code>s with <code>$</code> 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 <em>should</em> be consistent within projects.</li>
</ul>
<h4 id="descriptive-names">Descriptive names</h4>
<p>Names <em>must</em> 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.</p>
<ul>
<li><strong>Exception</strong>: Variables that are in scope for 10 lines or fewer, including
arguments that are <em>not</em> part of an exported API, <em>may</em> use short (e.g.
single letter) variable names.</li>
</ul>
<h3 id="file-encoding-utf-8">File encoding: UTF-8</h3>
<p>For non-ASCII characters, use the actual Unicode character (e.g. <code>∞</code>). For
non-printable characters, the equivalent hex or Unicode escapes (e.g. <code>\u221e</code>)
can be used along with an explanatory comment.</p>
<pre><code class="language-ts good">// Perfectly clear, even without a comment.
const units = 'μs';
// Use escapes for non-printable characters.
const output = '\ufeff' + content; // byte order mark
</code></pre>
<pre><code class="language-ts bad">// Hard to read and prone to mistakes, even with the comment.
const units = '\u03bcs'; // Greek letter mu, 's'
// The reader has no idea what this is.
const output = '\ufeff' + content;
</code></pre>
<h3 id="comments-documentation">Comments & Documentation</h3>
<h4 id="jsdoc-vs-comments">JSDoc vs comments</h4>
<p>There are two types of comments, JSDoc (<code>/** ... */</code>) and non-JSDoc ordinary
comments (<code>// ...</code> or <code>/* ... */</code>).</p>
<ul>
<li>Use <code>/** JSDoc */</code> comments for documentation, i.e. comments a user of the
code should read.</li>
<li>Use <code>// line comments</code> for implementation comments, i.e. comments that only
concern the implementation of the code itself.</li>
</ul>
<p>JSDoc comments are understood by tools (such as editors and documentation
generators), while ordinary comments are only for other humans.</p>
<h4 id="jsdoc-rules-follow-the-javascript-style">JSDoc rules follow the JavaScript style</h4>
<p>In general, follow the
<a href="https://google.github.io/styleguide/jsguide.html#jsdoc">JavaScript style guide's rules for JSDoc</a>,
sections 7.1 - 7.5. The remainder of this section describes exceptions to those
rules.</p>
<h4 id="document-all-top-level-exports-of-modules">Document all top-level exports of modules</h4>
<p>Use <code>/** JSDoc */</code> comments to communicate information to the users of your
code. Avoid merely restating the property or parameter name. You <em>should</em> also
document all properties and methods (exported/public or not) whose purpose is
not immediately obvious from their name, as judged by your reviewer.</p>
<p>Exception: Symbols that are only exported to be consumed by tooling, such as
@NgModule classes, do not require comments.</p>
<h4 id="omit-comments-that-are-redundant-with-typescript">Omit comments that are redundant with TypeScript</h4>
<p>For example, do not declare types in <code>@param</code> or <code>@return</code> blocks, do not write
<code>@implements</code>, <code>@enum</code>, <code>@private</code> etc. on code that uses the <code>implements</code>,
<code>enum</code>, <code>private</code> etc. keywords.</p>
<h4 id="do-not-use-override">Do not use <code>@override</code></h4>
<p>Do not use <code>@override</code> in TypeScript source code.</p>
<p><code>@override</code> is not enforced by the compiler, which is surprising and leads to
annotations and implementation going out of sync. Including it purely for
documentation purposes is confusing.</p>
<h4 id="redundant-comments">Make comments that actually add information</h4>
<p>For non-exported symbols, sometimes the name and type of the function or
parameter is enough. Code will <em>usually</em> benefit from more documentation than
just variable names though!</p>
<ul>
<li><p>Avoid comments that just restate the parameter name and type, e.g.</p>
<pre><code class="language-ts bad">/** @param fooBarService The Bar service for the Foo application. */
</code></pre></li>
<li><p>Because of this rule, <code>@param</code> and <code>@return</code> lines are only required when
they add information, and may otherwise be omitted.</p>
<pre><code class="language-ts good">/**
* POSTs the request to start coffee brewing.
* @param amountLitres The amount to brew. Must fit the pot size!
*/
brew(amountLitres: number, logger: Logger) {
// ...
}
</code></pre></li>
</ul>
<h4 id="parameter-property-comments">Parameter property comments</h4>
<p>A parameter property is when a class declares a field and a constructor
parameter in a single declaration, by marking a parameter in the constructor.
E.g. <code>constructor(private readonly foo: Foo)</code>, declares that the class has a
<code>foo</code> field.</p>
<p>To document these fields, use JSDoc's <code>@param</code> annotation. Editors display the
description on constructor calls and property accesses.</p>
<pre><code class="language-ts good">/** This class demonstrates how parameter properties are documented. */
class ParamProps {
/**
* @param percolator The percolator used for brewing.
* @param beans The beans to brew.
*/
constructor(
private readonly percolator: Percolator,
private readonly beans: CoffeeBean[]) {}
}
</code></pre>
<pre><code class="language-ts good">/** This class demonstrates how ordinary fields are documented. */
class OrdinaryClass {
/** The bean that will be used in the next call to brew(). */
nextBean: CoffeeBean;
constructor(initialBean: CoffeeBean) {
this.nextBean = initialBean;
}
}
</code></pre>
<h4 id="comments-when-calling-a-function">Comments when calling a function</h4>
<p>If needed, document parameters at call sites inline using block comments. Also
consider named parameters using object literals and destructuring. The exact
formatting and placement of the comment is not prescribed.</p>
<pre><code class="language-ts good">// Inline block comments for parameters that'd be hard to understand:
new Percolator().brew(/* amountLitres= */ 5);
// Also consider using named arguments and destructuring parameters (in brew's declaration):
new Percolator().brew({amountLitres: 5});
</code></pre>
<pre><code class="language-ts good">/** An ancient {@link CoffeeBrewer} */
export class Percolator implements CoffeeBrewer {
/**
* Brews coffee.
* @param amountLitres The amount to brew. Must fit the pot size!
*/
brew(amountLitres: number) {
// This implementation creates terrible coffee, but whatever.
// TODO(b/12345): Improve percolator brewing.
}
}
</code></pre>
<h4 id="place-documentation-prior-to-decorators">Place documentation prior to decorators</h4>
<p>When a class, method, or property have both decorators like <code>@Component</code> and
JsDoc, please make sure to write the JsDoc before the decorator.</p>
<ul>
<li><p>Do not write JsDoc between the Decorator and the decorated statement.</p>
<pre><code class="language-ts bad">@Component({
selector: 'foo',
template: 'bar',
})
/** Component that prints "bar". */
export class FooComponent {}
</code></pre></li>
<li><p>Write the JsDoc block before the Decorator.</p>
<pre><code class="language-ts good">/** Component that prints "bar". */
@Component({
selector: 'foo',
template: 'bar',
})
export class FooComponent {}
</code></pre></li>
</ul>
<h2 id="language-rules">Language Rules</h2>
<h3 id="visibility">Visibility</h3>
<p>Restricting visibility of properties, methods, and entire types helps with
keeping code decoupled.</p>
<ul>
<li>Limit symbol visibility as much as possible.</li>
<li>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.</li>
<li>TypeScript symbols are public by default. Never use the <code>public</code> modifier
except when declaring non-readonly public parameter properties (in
constructors).</li>
</ul>
<pre><code class="language-ts bad">class Foo {
public bar = new Bar(); // BAD: public modifier not needed
constructor(public readonly baz: Baz) {} // BAD: readonly implies it's a property which defaults to public
}
</code></pre>
<pre><code class="language-ts good">class Foo {
bar = new Bar(); // GOOD: public modifier not needed
constructor(public baz: Baz) {} // public modifier allowed
}
</code></pre>
<p>See also <a href="#export-visibility">export visibility</a> below.</p>
<h3 id="constructors">Constructors</h3>
<p>Constructor calls must use parentheses, even when no arguments are passed:</p>
<pre><code class="language-ts bad">const x = new Foo;
</code></pre>
<pre><code class="language-ts good">const x = new Foo();
</code></pre>
<p>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, modifiers or
parameter decorators should not be omitted even if the body of the constructor
is empty.</p>
<pre><code class="language-ts bad">class UnnecessaryConstructor {
constructor() {}
}
</code></pre>
<pre><code class="language-ts bad">class UnnecessaryConstructorOverride extends Base {
constructor(value: number) {
super(value);
}
}
</code></pre>
<pre><code class="language-ts good">class DefaultConstructor {
}
class ParameterProperties {
constructor(private myService) {}
}
class ParameterDecorators {
constructor(@SideEffectDecorator myService) {}
}
class NoInstantiation {
private constructor() {}
}
</code></pre>
<h3 id="class-members">Class Members</h3>
<h4 id="private-fields">No <code>#private</code> fields</h4>
<p>Do not use private fields (also known as private identifiers):</p>
<pre><code class="language-ts bad">class Clazz {
#ident = 1;
}
</code></pre>
<p>Instead, use TypeScript's visibility annotations:</p>
<pre><code class="language-ts good">class Clazz {
private ident = 1;
}
</code></pre>
<section class="zippy">
Why?
<p> 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.</p>
</section>
<h4 id="use-readonly">Use <code>readonly</code></h4>
<p>Mark properties that are never reassigned outside of the constructor with the
<code>readonly</code> modifier (these need not be deeply immutable).</p>
<h4 id="parameter-properties">Parameter properties</h4>
<p>Rather than plumbing an obvious initializer through to a class member, use a
TypeScript
<a href="https://www.typescriptlang.org/docs/handbook/classes.html#parameter-properties">parameter property</a>.</p>
<pre><code class="language-ts bad">class Foo {
private readonly barService: BarService;
constructor(barService: BarService) {
this.barService = barService;
}
}
</code></pre>
<pre><code class="language-ts good">class Foo {
constructor(private readonly barService: BarService) {}
}
</code></pre>
<p>If the parameter property needs documentation,
<a href="#parameter-property-comments">use an <code>@param</code> JSDoc tag</a>.</p>
<h4 id="field-initializers">Field initializers</h4>
<p>If a class member is not a parameter, initialize it where it's declared, which
sometimes lets you drop the constructor entirely.</p>
<pre><code class="language-ts bad">class Foo {
private readonly userList: string[];
constructor() {
this.userList = [];
}
}
</code></pre>
<pre><code class="language-ts good">class Foo {
private readonly userList: string[] = [];
}
</code></pre>
<h4 id="properties-used-outside-of-class-lexical-scope">Properties used outside of class lexical scope</h4>
<p>Properties used from outside the lexical scope of their containing class, such
as an AngularJS controller's properties used from a template, must not use
<code>private</code> visibility, as they are used outside of the lexical scope of their
containing class.</p>
<p>Prefer <code>public</code> visibility for these properties, however <code>protected</code> visibility
can also be used as needed. For example, Angular and Polymer template properties
should use <code>public</code>, but AngularJS should use <code>protected</code>.</p>
<p>TypeScript code must not not use <code>obj['foo']</code> to bypass the visibility of a
property</p>
<section class="zippy">
Why?
<p>When a property is <code>private</code>, 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.</p>
<p>Though it may appear that <code>obj['foo']</code> can bypass visibility in the TypeScript
compiler, this pattern can be broken by rearranging the build rules,
and also violates <a href="#optimization-compatibility">optimization compatibility</a>.
</p></section>
<h4>Getters and Setters (Accessors)</h4>
<p>Getters and setters for class members may be used. The getter method must be a
<a href="https://en.wikipedia.org/wiki/Pure_function">pure function</a> (i.e., result is
consistent and has no side effects). They are also useful as a means of
restricting the visibility of internal or verbose implementation details (shown
below).</p>
<pre><code class="language-ts good">class Foo {
constructor(private readonly someService: SomeService) {}
get someMember(): string {
return this.someService.someVariable;
}
set someMember(newValue: string) {
this.someService.someVariable = newValue;
}
}
</code></pre>
<p>If an accessor is used to hide a class property, the hidden property may be
prefixed or suffixed with any whole word, like <code>internal</code> or <code>wrapped</code>. 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 <q>pass-through</q> accessors only for the purpose of hiding a property.
Instead, make the property public (or consider making it <code>readonly</code> rather than
just defining a getter with no setter).</p>
<pre><code class="language-ts good">class Foo {
private wrappedBar = '';
get bar() {
return this.wrappedBar || 'bar';
}
set bar(wrapped: string) {
this.wrappedBar = wrapped.trim();
}
}
</code></pre>
<pre><code class="language-ts bad">class Bar {
private barInternal = '';
// Neither of these accessors have logic, so just make bar public.
get bar() {
return this.barInternal;
}
set bar(value: string) {
this.barInternal = value;
}
}
</code></pre>
<h3 id="primitive-types-wrapper-classes">Primitive Types & Wrapper Classes</h3>
<p>TypeScript code must not instantiate the wrapper classes for the primitive types
<code>String</code>, <code>Boolean</code>, and <code>Number</code>. Wrapper classes have surprising behaviour,
such as <code>new Boolean(false)</code> evaluating to <code>true</code>.</p>
<pre><code class="language-ts bad">const s = new String('hello');
const b = new Boolean(false);
const n = new Number(5);
</code></pre>
<pre><code class="language-ts good">const s = 'hello';
const b = false;
const n = 5;
</code></pre>
<h3 id="array-constructor">Array constructor</h3>
<p>TypeScript code must not use the <code>Array()</code> constructor, with or without <code>new</code>.
It has confusing and contradictory usage:</p>
<pre><code class="language-ts bad">const a = new Array(2); // [undefined, undefined]
const b = new Array(2, 3); // [2, 3];
</code></pre>
<p>Instead, always use bracket notation to initialize arrays, or <code>from</code> to
initialize an <code>Array</code> with a certain size:</p>
<pre><code class="language-ts good">const a = [2];
const b = [2, 3];
// Equivalent to Array(2):
const c = [];
c.length = 2;
// [0, 0, 0, 0, 0]
Array.from<number>({length: 5}).fill(0);
</code></pre>
<h3 id="type-coercion">Type coercion</h3>
<p>TypeScript code may use the <code>String()</code> and <code>Boolean()</code> (note: no <code>new</code>!)
functions, string template literals, or <code>!!</code> to coerce types.</p>
<pre><code class="language-ts good">const bool = Boolean(false);
const str = String(aNumber);
const bool2 = !!str;
const str2 = `result: ${bool2}`;
</code></pre>
<p>Using string concatenation to cast to string is discouraged, as we check that
operands to the plus operator are of matching types.</p>
<p>Code must use <code>Number()</code> to parse numeric values, and <em>must</em> check its return
for <code>NaN</code> values explicitly, unless failing to parse is impossible from context.</p>
<p>Note: <code>Number('')</code>, <code>Number(' ')</code>, and <code>Number('\t')</code> would return <code>0</code> instead
of <code>NaN</code>. <code>Number('Infinity')</code> and <code>Number('-Infinity')</code> would return <code>Infinity</code>
and <code>-Infinity</code> respectively. These cases may require special handling.</p>
<pre><code class="language-ts good">const aNumber = Number('123');
if (isNaN(aNumber)) throw new Error(...); // Handle NaN if the string might not contain a number
assertFinite(aNumber, ...); // Optional: if NaN cannot happen because it was validated before.
</code></pre>
<p>Code must not use unary plus (<code>+</code>) 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.</p>
<pre><code class="language-ts bad">const x = +y;
</code></pre>
<p>Code must also not use <code>parseInt</code> or <code>parseFloat</code> 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 <code>12
dwarves</code> as <code>12</code>).</p>
<pre><code class="language-ts bad">const n = parseInt(someString, 10); // Error prone,
const f = parseFloat(someString); // regardless of passing a radix.
</code></pre>
<p>Code that must parse using a radix <em>must</em> check that its input is a number
before calling into <code>parseInt</code>;</p>
<pre><code class="language-ts good">if (!/^[a-fA-F0-9]+$/.test(someString)) throw new Error(...);
// Needed to parse hexadecimal.
// tslint:disable-next-line:ban
const n = parseInt(someString, 16); // Only allowed for radix != 10
</code></pre>
<p>Use <code>Number()</code> followed by <code>Math.floor</code> or <code>Math.trunc</code> (where available) to
parse integer numbers:</p>
<pre><code class="language-ts good">let f = Number(someString);
if (isNaN(f)) handleError();
f = Math.floor(f);
</code></pre>
<p>Do not use explicit boolean coercions in conditional clauses that have implicit
boolean coercion. Those are the conditions in an <code>if</code>, <code>for</code> and <code>while</code>
statements.</p>
<pre><code class="language-ts bad">const foo: MyInterface|null = ...;
if (!!foo) {...}
while (!!foo) {...}
</code></pre>
<pre><code class="language-ts good">const foo: MyInterface|null = ...;
if (foo) {...}
while (foo) {...}
</code></pre>
<p>Code may use explicit comparisons:</p>
<pre><code class="language-ts good">// Explicitly comparing > 0 is OK:
if (arr.length > 0) {...}
// so is relying on boolean coercion:
if (arr.length) {...}
</code></pre>
<h3 id="variables">Variables</h3>
<p>Always use <code>const</code> or <code>let</code> to declare variables. Use <code>const</code> by default, unless
a variable needs to be reassigned. Never use <code>var</code>.</p>
<pre><code class="language-ts good">const foo = otherValue; // Use if "foo" never changes.
let bar = someValue; // Use if "bar" is ever assigned into later on.
</code></pre>
<p><code>const</code> and <code>let</code> are block scoped, like variables in most other languages.
<code>var</code> in JavaScript is function scoped, which can cause difficult to understand
bugs. Don't use it.</p>
<pre><code class="language-ts bad">var foo = someValue; // Don't use - var scoping is complex and causes bugs.
</code></pre>
<p>Variables must not be used before their declaration.</p>
<h3 id="exceptions">Exceptions</h3>
<p>Always use <code>new Error()</code> when instantiating exceptions, instead of just calling
<code>Error()</code>. Both forms create a new <code>Error</code> instance, but using <code>new</code> is more
consistent with how other objects are instantiated.</p>
<pre><code class="language-ts good">throw new Error('Foo is not a valid bar.');
</code></pre>
<pre><code class="language-ts bad">throw Error('Foo is not a valid bar.');
</code></pre>
<h3 id="iterating-objects">Iterating objects</h3>
<p>Iterating objects with <code>for (... in ...)</code> is error prone. It will include
enumerable properties from the prototype chain.</p>
<p>Do not use unfiltered <code>for (... in ...)</code> statements:</p>
<pre><code class="language-ts bad">for (const x in someObj) {
// x could come from some parent prototype!
}
</code></pre>
<p>Either filter values explicitly with an <code>if</code> statement, or use <code>for (... of
Object.keys(...))</code>.</p>
<pre><code class="language-ts good">for (const x in someObj) {
if (!someObj.hasOwnProperty(x)) continue;
// now x was definitely defined on someObj
}
for (const x of Object.keys(someObj)) { // note: for _of_!
// now x was definitely defined on someObj
}
for (const [key, value] of Object.entries(someObj)) { // note: for _of_!
// now key was definitely defined on someObj
}
</code></pre>
<h3 id="iterating-containers">Iterating containers</h3>
<p>Do not use <code>for (... in ...)</code> to iterate over arrays. It will counterintuitively
give the array's indices (as strings!), not values:</p>
<pre><code class="language-ts bad">for (const x in someArray) {
// x is the index!
}
</code></pre>
<p>Use <code>for (... of someArr)</code> or vanilla <code>for</code> loops with indices to iterate over
arrays.</p>
<pre><code class="language-ts good">for (const x of someArr) {
// x is a value of someArr.
}
for (let i = 0; i < someArr.length; i++) {
// Explicitly count if the index is needed, otherwise use the for/of form.
const x = someArr[i];
// ...
}
for (const [i, x] of someArr.entries()) {
// Alternative version of the above.
}
</code></pre>
<p>Do not use <code>Array.prototype.forEach</code>, <code>Set.prototype.forEach</code>, and
<code>Map.prototype.forEach</code>. They make code harder to debug and defeat some useful
compiler checks (e.g. reachability).</p>
<pre><code class="language-ts bad">someArr.forEach((item, index) => {
someFn(item, index);
});
</code></pre>
<section class="zippy">
Why?
<p>Consider this code:</p>
<pre><code class="language-ts bad">let x: string|null = 'abc';
myArray.forEach(() => { x.charAt(0); });
</code></pre>
<p>You can recognize that this code is fine: <code>x</code> isn't null and it doesn't change
before it is accessed. But the compiler cannot know that this <code>.forEach()</code> call
doesn't hang on to the closure that was passed in and call it at some later
point, maybe after <code>x</code> was set to null, so it flags this code as an error. The
equivalent for-of loop is fine.</p>
<p>
<a href="https://www.typescriptlang.org/play?#code/DYUwLgBAHgXBDOYBOBLAdgcwD5oK7GAgF4IByAQwCMBjUgbgCgBtAXQDoAzAeyQFFzqACwAUwgJTEAfBADeDCNDZDySAIJhhABjGMAvjoYNQkAJ5xEqTDnyESFGvQbckEYdS5pEEAPoQuHCFYJOQUTJUEVdS0DXQYgA">See the error and non-error in the playground</a>
</p>
<p>In practice, variations of this limitation of control flow analysis show up in
more complex codepaths where it is more surprising.
</p></section>
<h3 id="using-the-spread-operator">Using the spread operator</h3>
<p>Using the spread operator <code>[...foo]; {...bar}</code> is a convenient shorthand for
copying arrays and objects. When using the spread operator on objects, later
values replace earlier values at the same key.</p>
<pre><code class="language-ts good">const foo = {
num: 1,
};
const foo2 = {
...foo,
num: 5,
};
const foo3 = {
num: 5,
...foo,
}
foo2.num === 5;
foo3.num === 1;
</code></pre>
<p>When using the spread operator, the value being spread must match what is being
created. That is, when creating an object, only objects may be used with the
spread operator; when creating an array, only spread iterables. Primitives,
including <code>null</code> and <code>undefined</code>, may never be spread.</p>
<pre><code class="language-ts bad">const foo = {num: 7};
const bar = {num: 5, ...(shouldUseFoo && foo)}; // might be undefined
// Creates {0: 'a', 1: 'b', 2: 'c'} but has no length
const fooStrings = ['a', 'b', 'c'];
const ids = {...fooStrings};
</code></pre>
<pre><code class="language-ts good">const foo = shouldUseFoo ? {num: 7} : {};
const bar = {num: 5, ...foo};
const fooStrings = ['a', 'b', 'c'];
const ids = [...fooStrings, 'd', 'e'];
</code></pre>
<h3 id="control-flow-statements-blocks">Control flow statements & blocks</h3>
<p>Control flow statements spanning multiple lines always use blocks for the
containing code.</p>
<pre><code class="language-ts good">for (let i = 0; i < x; i++) {
doSomethingWith(i);
andSomeMore();
}
if (x) {
doSomethingWithALongMethodName(x);
}
</code></pre>
<pre><code class="language-ts bad">if (x)
x.doFoo();
for (let i = 0; i < x; i++)
doSomethingWithALongMethodName(i);
</code></pre>
<p>The exception is that <code>if</code> statements fitting on one line may elide the block.</p>
<pre><code class="language-ts good">if (x) x.doFoo();
</code></pre>
<h3 id="switch-statements">Switch Statements</h3>
<p>All <code>switch</code> statements must contain a <code>default</code> statement group, even if it
contains no code.</p>
<pre><code class="language-ts good">switch (x) {
case Y:
doSomethingElse();
break;
default:
// nothing to do.
}
</code></pre>
<p>Non-empty statement groups (<code>case ...</code>) may not fall through (enforced by the
compiler):</p>
<pre><code class="language-ts bad">switch (x) {
case X:
doSomething();
// fall through - not allowed!
case Y:
// ...
}
</code></pre>
<p>Empty statement groups are allowed to fall through:</p>
<pre><code class="language-ts good">switch (x) {
case X:
case Y:
doSomething();
break;
default: // nothing to do.
}
</code></pre>
<h3 id="equality-checks">Equality Checks</h3>
<p>Always use triple equals (<code>===</code>) and not equals (<code>!==</code>). 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
<a href="https://dorey.github.io/JavaScript-Equality-Table/">JavaScript equality table</a>.</p>
<pre><code class="language-ts bad">if (foo == 'bar' || baz != bam) {
// Hard to understand behaviour due to type coercion.
}
</code></pre>
<pre><code class="language-ts good">if (foo === 'bar' || baz !== bam) {
// All good here.
}
</code></pre>
<p><strong>Exception</strong>: Comparisons to the literal <code>null</code> value may use the <code>==</code> and <code>!=</code>
operators to cover both <code>null</code> and <code>undefined</code> values.</p>
<pre><code class="language-ts good">if (foo == null) {
// Will trigger when foo is null or undefined.
}
</code></pre>
<h3 id="function-declarations">Function Declarations</h3>
<p>Use <code>function foo() { ... }</code> to declare named functions, including functions in
nested scopes, e.g. within another function.</p>
<p>Use function declarations instead of assigning a function expression into a
local variable (<del><code>const x = function() {...};</code></del>). TypeScript already disallows
rebinding functions, so preventing overwriting a function declaration by using
<code>const</code> is unnecessary.</p>
<p>Exception: Use arrow functions assigned to variables instead of function
declarations if the function accesses the outer scope's <code>this</code>.</p>