0
# Style and Formatting Rules
1
2
Rules focused on code style, naming conventions, and formatting preferences for TypeScript code. These rules help maintain consistent code appearance and readability across projects.
3
4
## Capabilities
5
6
### Naming Conventions
7
8
Rules that enforce consistent naming patterns for various code elements.
9
10
```typescript { .api }
11
/**
12
* Enforce naming conventions for variables, functions, classes, etc.
13
*/
14
"naming-convention": RuleModule;
15
```
16
17
**Usage Examples:**
18
19
```typescript
20
// Configuration example for naming-convention
21
{
22
"@typescript-eslint/naming-convention": [
23
"error",
24
{
25
"selector": "variable",
26
"format": ["camelCase", "UPPER_CASE"]
27
},
28
{
29
"selector": "function",
30
"format": ["camelCase"]
31
},
32
{
33
"selector": "typeLike",
34
"format": ["PascalCase"]
35
},
36
{
37
"selector": "interface",
38
"format": ["PascalCase"],
39
"prefix": ["I"]
40
}
41
]
42
}
43
44
// ❌ Bad
45
const user_name = 'john'; // Should be camelCase
46
function Process_Data() {} // Should be camelCase
47
interface userInterface {} // Should be PascalCase
48
49
// ✅ Good
50
const userName = 'john';
51
const MAX_RETRIES = 3;
52
function processData() {}
53
interface IUserInterface {}
54
```
55
56
### Array and Object Styling
57
58
Rules that enforce consistent styling for arrays and objects.
59
60
```typescript { .api }
61
/**
62
* Require consistently using either T[] or Array<T> for arrays
63
*/
64
"array-type": RuleModule;
65
66
/**
67
* Enforce consistent indexed object style
68
*/
69
"consistent-indexed-object-style": RuleModule;
70
71
/**
72
* Enforce consistent class literal property style
73
*/
74
"class-literal-property-style": RuleModule;
75
76
/**
77
* Disallow Array constructors
78
*/
79
"no-array-constructor": RuleModule;
80
```
81
82
**Usage Examples:**
83
84
```typescript
85
// ❌ Bad - array-type (with array-simple preference)
86
const users: Array<User> = []; // Should use T[]
87
const matrix: (number | string)[][] = []; // Complex type, Array<> ok
88
89
// ✅ Good
90
const users: User[] = [];
91
const matrix: Array<Array<number | string>> = [];
92
93
// ❌ Bad - class-literal-property-style (with fields preference)
94
class User {
95
get name(): string { return this._name; } // Should be field
96
set name(value: string) { this._name = value; }
97
}
98
99
// ✅ Good
100
class User {
101
public name: string;
102
}
103
```
104
105
### Type Assertion and Annotation Styling
106
107
Rules that govern how type assertions and annotations are formatted.
108
109
```typescript { .api }
110
/**
111
* Enforce consistent type assertions
112
*/
113
"consistent-type-assertions": RuleModule;
114
115
/**
116
* Enforce consistent generic constructors
117
*/
118
"consistent-generic-constructors": RuleModule;
119
120
/**
121
* Enforce consistent method signature style
122
*/
123
"method-signature-style": RuleModule;
124
125
/**
126
* Enforce consistent type definitions as interface or type
127
*/
128
"consistent-type-definitions": RuleModule;
129
130
/**
131
* Enforce non-nullable type assertion style
132
*/
133
"non-nullable-type-assertion-style": RuleModule;
134
```
135
136
**Usage Examples:**
137
138
```typescript
139
// ❌ Bad - consistent-type-assertions (with as preference)
140
const user = <User>data; // Should use 'as'
141
142
// ✅ Good
143
const user = data as User;
144
145
// ❌ Bad - method-signature-style (with property preference)
146
interface Calculator {
147
add(a: number, b: number): number; // Should be property style
148
}
149
150
// ✅ Good
151
interface Calculator {
152
add: (a: number, b: number) => number;
153
}
154
155
// ❌ Bad - consistent-generic-constructors (with constructor preference)
156
const users = new Map<string, User>(); // Should use constructor
157
158
// ✅ Good
159
const users: Map<string, User> = new Map();
160
```
161
162
### Member and Parameter Ordering
163
164
Rules that enforce consistent ordering of class members, object properties, and parameters.
165
166
```typescript { .api }
167
/**
168
* Require consistent member declaration ordering
169
*/
170
"member-ordering": RuleModule;
171
172
/**
173
* Enforce default parameters to be last
174
*/
175
"default-param-last": RuleModule;
176
177
/**
178
* Require getter and setter pairs to be adjacent
179
*/
180
"related-getter-setter-pairs": RuleModule;
181
182
/**
183
* Enforce consistent sorting of type constituents
184
*/
185
"sort-type-constituents": RuleModule;
186
```
187
188
**Usage Examples:**
189
190
```typescript
191
// ❌ Bad - member-ordering (with fields-first preference)
192
class User {
193
public getName(): string { return this.name; } // Method before field
194
public name: string;
195
private constructor(name: string) { this.name = name; }
196
}
197
198
// ✅ Good
199
class User {
200
public name: string;
201
202
private constructor(name: string) {
203
this.name = name;
204
}
205
206
public getName(): string {
207
return this.name;
208
}
209
}
210
211
// ❌ Bad - sort-type-constituents
212
type Status = 'pending' | 'active' | 'inactive' | 'archived'; // Not sorted
213
214
// ✅ Good
215
type Status = 'active' | 'archived' | 'inactive' | 'pending'; // Alphabetically sorted
216
```
217
218
### Code Formatting and Layout
219
220
Rules that control code formatting, spacing, and layout.
221
222
```typescript { .api }
223
/**
224
* Enforce dot notation whenever possible
225
*/
226
"dot-notation": RuleModule;
227
228
/**
229
* Require or disallow trailing commas
230
*/
231
"comma-dangle": RuleModule;
232
233
/**
234
* Enforce consistent spacing around keywords
235
*/
236
"keyword-spacing": RuleModule;
237
238
/**
239
* Enforce consistent spacing before and after commas
240
*/
241
"comma-spacing": RuleModule;
242
243
/**
244
* Enforce consistent spacing inside braces
245
*/
246
"object-curly-spacing": RuleModule;
247
248
/**
249
* Enforce consistent spacing around semicolons
250
*/
251
"semi-spacing": RuleModule;
252
```
253
254
**Usage Examples:**
255
256
```typescript
257
// ❌ Bad - dot-notation
258
const value = obj['property']; // Should use dot notation
259
260
// ✅ Good
261
const value = obj.property;
262
263
// ❌ Bad - comma-dangle (with always-multiline preference)
264
const config = {
265
api: '/api/v1',
266
timeout: 5000 // Missing trailing comma
267
};
268
269
// ✅ Good
270
const config = {
271
api: '/api/v1',
272
timeout: 5000,
273
};
274
```
275
276
### Literal and Expression Styling
277
278
Rules that govern how literals and expressions are formatted.
279
280
```typescript { .api }
281
/**
282
* Disallow magic numbers
283
*/
284
"no-magic-numbers": RuleModule;
285
286
/**
287
* Require literal enum members
288
*/
289
"prefer-literal-enum-member": RuleModule;
290
291
/**
292
* Prefer initializing enum members
293
*/
294
"prefer-enum-initializers": RuleModule;
295
296
/**
297
* Prefer as const over literal type
298
*/
299
"prefer-as-const": RuleModule;
300
301
/**
302
* Disallow unnecessary template expressions
303
*/
304
"no-unnecessary-template-expression": RuleModule;
305
```
306
307
**Usage Examples:**
308
309
```typescript
310
// ❌ Bad - no-magic-numbers
311
setTimeout(callback, 3000); // Magic number
312
313
// ✅ Good
314
const TIMEOUT_MS = 3000;
315
setTimeout(callback, TIMEOUT_MS);
316
317
// ❌ Bad - prefer-literal-enum-member
318
enum Status {
319
Active = getValue(), // Should be literal
320
Inactive = 'inactive'
321
}
322
323
// ✅ Good
324
enum Status {
325
Active = 'active',
326
Inactive = 'inactive'
327
}
328
329
// ❌ Bad - prefer-as-const
330
const colors = ['red', 'green', 'blue']; // Inferred as string[]
331
332
// ✅ Good
333
const colors = ['red', 'green', 'blue'] as const; // Readonly tuple
334
```
335
336
### Template and String Styling
337
338
Rules that govern template literals and string formatting.
339
340
```typescript { .api }
341
/**
342
* Enforce template literal expressions to be of string type
343
*/
344
"restrict-template-expressions": RuleModule;
345
346
/**
347
* Disallow unnecessary template expressions
348
*/
349
"no-unnecessary-template-expression": RuleModule;
350
351
/**
352
* Prefer string starts/ends with over regex or indexOf
353
*/
354
"prefer-string-starts-ends-with": RuleModule;
355
356
/**
357
* Prefer regexp exec over string match
358
*/
359
"prefer-regexp-exec": RuleModule;
360
```
361
362
**Usage Examples:**
363
364
```typescript
365
// ❌ Bad - restrict-template-expressions
366
const message = `User count: ${users}`; // Object in template
367
368
// ✅ Good
369
const message = `User count: ${users.length}`;
370
371
// ❌ Bad - prefer-string-starts-ends-with
372
if (str.indexOf('prefix') === 0) {} // Should use startsWith
373
374
// ✅ Good
375
if (str.startsWith('prefix')) {}
376
377
// ❌ Bad - no-unnecessary-template-expression
378
const greeting = `Hello`; // Should use regular string
379
380
// ✅ Good
381
const greeting = 'Hello';
382
const dynamicGreeting = `Hello, ${name}!`; // Template needed
383
```
384
385
### Comment and Documentation Styling
386
387
Rules that govern comments and documentation formatting.
388
389
```typescript { .api }
390
/**
391
* Disallow @ts-<directive> comments or require descriptions
392
*/
393
"ban-ts-comment": RuleModule;
394
395
/**
396
* Prefer @ts-expect-error over @ts-ignore
397
*/
398
"prefer-ts-expect-error": RuleModule;
399
400
/**
401
* Disallow // tslint:<rule-flag> comments
402
*/
403
"ban-tslint-comment": RuleModule;
404
405
/**
406
* Disallow triple slash reference directives except types
407
*/
408
"triple-slash-reference": RuleModule;
409
```
410
411
**Usage Examples:**
412
413
```typescript
414
// ❌ Bad - prefer-ts-expect-error
415
// @ts-ignore // No description
416
const result = problematicFunction();
417
418
// ✅ Good
419
// @ts-expect-error - Known issue with third-party library types
420
const result = problematicFunction();
421
422
// ❌ Bad - ban-tslint-comment
423
/* tslint:disable */ // Should use ESLint disable comment
424
425
// ✅ Good
426
/* eslint-disable @typescript-eslint/no-explicit-any */
427
```
428
429
## Configuration Examples
430
431
### Strict Styling Rules
432
433
```json
434
{
435
"rules": {
436
"@typescript-eslint/naming-convention": [
437
"error",
438
{
439
"selector": "variable",
440
"format": ["camelCase", "UPPER_CASE"]
441
},
442
{
443
"selector": "function",
444
"format": ["camelCase"]
445
},
446
{
447
"selector": "typeLike",
448
"format": ["PascalCase"]
449
}
450
],
451
"@typescript-eslint/array-type": ["error", { "default": "array-simple" }],
452
"@typescript-eslint/consistent-type-assertions": ["error", { "assertionStyle": "as" }],
453
"@typescript-eslint/member-ordering": "error",
454
"@typescript-eslint/prefer-as-const": "error"
455
}
456
}
457
```
458
459
### Relaxed Styling Rules
460
461
```json
462
{
463
"rules": {
464
"@typescript-eslint/no-magic-numbers": "off",
465
"@typescript-eslint/array-type": "off",
466
"@typescript-eslint/consistent-type-definitions": ["warn", "interface"],
467
"@typescript-eslint/dot-notation": "warn"
468
}
469
}
470
```
471
472
## Types
473
474
```typescript { .api }
475
interface NamingConventionRule {
476
selector: 'variable' | 'function' | 'parameter' | 'property' | 'method'
477
| 'accessor' | 'enumMember' | 'class' | 'interface' | 'typeAlias'
478
| 'enum' | 'typeParameter';
479
format: ('camelCase' | 'PascalCase' | 'snake_case' | 'UPPER_CASE')[];
480
prefix?: string[];
481
suffix?: string[];
482
leadingUnderscore?: 'forbid' | 'allow' | 'require';
483
trailingUnderscore?: 'forbid' | 'allow' | 'require';
484
filter?: string | { regex: string; match: boolean };
485
}
486
487
interface MemberOrderingRule {
488
default?: MemberType[];
489
classes?: MemberType[];
490
classExpressions?: MemberType[];
491
interfaces?: MemberType[];
492
typeLiterals?: MemberType[];
493
}
494
495
type MemberType =
496
| 'signature'
497
| 'field'
498
| 'constructor'
499
| 'method'
500
| 'accessor'
501
| ['field', { visibility?: 'public' | 'protected' | 'private' }]
502
| string;
503
504
interface ArrayTypeRule {
505
default: 'array' | 'generic' | 'array-simple';
506
readonly?: 'array' | 'generic' | 'array-simple';
507
}
508
```