forked from google/styleguide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tsguide.html
2708 lines (2075 loc) · 93.7 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>
<p>go/tsstyle</p>
<section markdown="1">
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.
<p>There is no automatic deployment process for this version as it's pushed
on-demand by volunteers.
</p></section>
<p>This Style Guide uses <a href="https://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 <em>must</em> 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. See
<a href="#identifiers-constants">Constants</a> below.</td>
</tr>
<tr>
<td><code>#ident</code></td>
<td>private identifiers are never used.</td>
</tr>
</tbody>
</table>
<h4 id="identifiers-abbreviations">Abbreviations</h4>
<p>
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>
<h4 id="identifiers-dollar-sign">Dollar sign</h4>
<p>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>
<h4 id="identifiers-type-parameters">Type parameters</h4>
<p>Type parameters, like in <code>Array<T></code>, <em>may</em> use a single upper case character
(<code>T</code>) or <code>UpperCamelCase</code>.</p>
<h4 id="identifiers-test-names">Test names</h4>
<p>Test method names in Closure <code>testSuite</code>s and similar xUnit-style test
frameworks <em>may</em> be structured with <code>_</code> separators, e.g. <code>testX_whenY_doesZ()</code>.</p>
<h4 id="identifiers-underscore-prefix-suffix"><code>_</code> prefix/suffix</h4>
<p>Identifiers must not use <code>_</code> as a prefix or suffix.</p>
<p>This also means that <code>_</code> <em>must not</em> be used as an identifier by itself (e.g. to
indicate a parameter is unused).</p>
<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>
<h4 id="identifiers-imports">Imports</h4>
<p>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>
<h4 id="identifiers-constants">Constants</h4>
<p><strong>Immutable</strong>: <code>CONSTANT_CASE</code> indicates that a value is <em>intended</em> to not be
changed, and <em>may</em> 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><strong>Global</strong>: Only symbols declared on the module level, static fields of module
level classes, and values of module level enums, <em>may</em> use <code>CONST_CASE</code>. 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 <em>must</em> use <code>lowerCamelCase</code>.</p>
<p>If a value is an arrow function that implements an interface, then it <em>may</em> be
declared <code>lowerCamelCase</code>.</p>
<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 <em>must</em> 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>
<blockquote>
<p>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
<a href="#properties-used-outside-of-class-lexical-scope">access modifiers</a>.</p>
</blockquote>
<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="syntax-no-line-continuations">No line continuations</h3>
<p>Do not use <em>line continuations</em> (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.</p>
<p>Disallowed:</p>
<pre><code class="language-ts bad">const LONG_STRING = 'This is a very long string that far exceeds the 80 \
column limit. It unfortunately contains long stretches of spaces due \
to how the continued lines are indented.';
</code></pre>
<p>Instead, write</p>
<pre><code class="language-ts good">const LONG_STRING = 'This is a very long string that far exceeds the 80 ' +
'column limit. It does not contain long stretches of spaces since ' +
'the concatenated strings are cleaner.';
</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><a id="do-not-use-override"></a></p>
<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>, <code>@override</code> etc. on code that uses the
<code>implements</code>, <code>enum</code>, <code>private</code>, <code>override</code> etc. keywords.</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 <em>may</em> 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
<a href="https://www.typescriptlang.org/docs/handbook/2/classes.html#parameter-properties">parameter property</a>
is a constructor parameter that is prefixed by one of the modifiers <code>private</code>,
<code>protected</code>, <code>public</code>, or <code>readonly</code>. A parameter property declares both a
parameter and an instance property, and implicitly assigns into it. For example,
<code>constructor(private readonly foo: Foo)</code>, declares that the constructor takes a
parameter <code>foo</code>, but also declares a private readonly property <code>foo</code>, and
assigns the parameter into that property before executing the remainder of the
constructor.</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>
<p>TypeScript language features which are not discussed in this style guide <em>may</em>
be used with no recommendations of their usage.</p>
<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 <em>must</em> 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, visibility
modifiers or parameter decorators <em>should not</em> 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" markdown="1">
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/2/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 Angular component's properties used from a template, <em>must not</em> use
<code>private</code> visibility, as they are used outside of the lexical scope of their
containing class.</p>
<p>Use either <code>protected</code> or <code>public</code> as appropriate to the property in question.
Angular and AngularJS template properties should use <code>protected</code>, but Polymer
should use <code>public</code>.</p>
<p>TypeScript code <em>must not</em> use <code>obj['foo']</code> to bypass the visibility of a
property. See
<a href="http://go/typescript-testing#export-private-visibility">testing and private visibility</a>
if you want to access protected fields from a test.</p>
<section class="zippy" markdown="1">
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 might 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 <em>may</em> be used. The getter method <em>must</em> 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 <em>may</em> 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 <em>must</em> 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>
<h4 id="static-this">Static this references</h4>
<p>Code <em>must not</em> use <code>this</code> in a static context.</p>
<p>JavaScript allows accessing static fields through <code>this</code>. Different from other
languages, static fields are also inherited.</p>
<pre><code class="bad">class ShoeStore {
static storage: Storage = ...;
static isAvailable(s: Shoe) {
// Bad: do not use `this` in a static method.
return this.storage.has(s.id);
}
}
class EmptyShoeStore extends ShoeStore {
static storage: Storage = EMPTY_STORE; // overrides storage from ShoeStore
}
</code></pre>
<section class="zippy">
Why?
<p>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.</p>
<p>This code also encourages an anti-pattern of having substantial static state,
which causes problems with testability.</p>
</section>
<h3 id="primitive-types-wrapper-classes">Primitive Types & Wrapper Classes</h3>
<p>TypeScript code <em>must not</em> instantiate the wrapper classes for the primitive
types <code>String</code>, <code>Boolean</code>, and <code>Number</code>. Wrapper classes have surprising
behavior, 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 <em>must not</em> 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 <em>may</em> 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>Values of enum types (including unions of enum types and other types) <em>must not</em>
be converted to booleans with <code>Boolean()</code> or <code>!!</code>, and must instead be compared
explicitly with comparison operators.</p>
<pre><code class="language-ts bad">enum SupportLevel {
NONE,
BASIC,
ADVANCED,
}
const level: SupportLevel = ...;
let enabled = Boolean(level);
const maybeLevel: SupportLevel|undefined = ...;
enabled = !!maybeLevel;
</code></pre>
<pre><code class="language-ts good">enum SupportLevel {
NONE,
BASIC,
ADVANCED,
}
const level: SupportLevel = ...;
let enabled = level !== SupportLevel.NONE;
const maybeLevel: SupportLevel|undefined = ...;
enabled = level !== undefined && level !== SupportLevel.NONE;
</code></pre>
<section class="zippy" markdown="1">
Why?
<p>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 <em>does</em> 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.
</p></section>
<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 <em>must</em> 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. Additionally, exponential notation such as
<code>Number('1e+309')</code> and <code>Number('-1e+309')</code> can overflow into <code>Infinity</code>. These
cases may require special handling.</p>
<pre><code class="language-ts good">const aNumber = Number('123');
if (!isFinite(aNumber)) throw new Error(...);
</code></pre>
<p>Code <em>must not</em> 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 also <em>must not</em> 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 requires parsing with a radix <em>must</em> check that its input contains
only appropriate digits for that radix 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>
<h4 id="type-coercion-implicit">Implicit coercion</h4>
<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><a href="#type-coercion">As with explicit conversions</a>, values of enum types (including
unions of enum types and other types) <em>must not</em> be implicitly coerced to
booleans, and must instead be compared explicitly with comparison operators.</p>
<pre><code class="language-ts bad">enum SupportLevel {
NONE,
BASIC,
ADVANCED,
}
const level: SupportLevel = ...;
if (level) {...}
const maybeLevel: SupportLevel|undefined = ...;
if (level) {...}
</code></pre>
<pre><code class="language-ts good">enum SupportLevel {
NONE,
BASIC,
ADVANCED,
}
const level: SupportLevel = ...;
if (level !== SupportLevel.NONE) {...}
const maybeLevel: SupportLevel|undefined = ...;
if (level !== undefined && level !== SupportLevel.NONE) {...}
</code></pre>
<p>Other types of values may be either implicitly coerced to booleans or compared
explicitly with comparison operators:</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 <em>must not</em> be used before their declaration.</p>
<h3 id="exceptions">Exceptions</h3>
<h4>Instantiate Errors using new</h4>
<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>
<h4>Only throw Errors</h4>
<p>JavaScript (and thus TypeScript) allow throwing arbitrary values. However if the
thrown value is not an <code>Error</code>, it does not get a stack trace filled in, making
debugging hard.</p>
<pre><code class="language-ts bad">// bad: does not get a stack trace.
throw 'oh noes!';
</code></pre>
<p>Instead, only throw (subclasses of) <code>Error</code>:</p>
<pre><code class="language-ts good">// Throw only Errors
throw new Error('oh noes!');
// ... or subtypes of Error.
class MyError extends Error {}
throw new MyError('my oh noes!');
</code></pre>
<h4>Catching & rethrowing</h4>
<p>When catching errors, code <em>should</em> assume that all thrown errors are instances
of <code>Error</code>.</p>
<section markdown="1">
<pre><code class="language-ts good">try {
doSomething();
} catch (e: unknown) {
// All thrown errors must be Error subtypes. Do not handle
// other possible values unless you know they are thrown.
assert(e, isInstanceOf(Error));
displayError(e.message);
// or rethrow:
throw e;
}
</code></pre>
</section>
<p>Exception handlers <em>must not</em> defensively handle non-<code>Error</code> types unless the
called API is conclusively known to throw non-<code>Error</code>s in violation of the above
rule. In that case, a comment should be included to specifically identify where
the non-<code>Error</code>s originate.</p>
<pre><code class="language-ts good">try {
badApiThrowingStrings();
} catch (e: unknown) {
// Note: bad API throws strings instead of errors.
if (typeof e === 'string') { ... }
}
</code></pre>
<section class="zippy" markdown="1">
Why?
<p>Avoid <a href="https://en.wikipedia.org/wiki/Defensive_programming#Offensive_programming">overly defensive programming</a>. Repeating the same
defenses against a problem that will not exist in most code leads to
boiler-plate code that is not useful.
</p></section>
<h3 id="iterating-objects">Iterating objects</h3>