/
no-unnecessary-condition.test.ts
721 lines (699 loc) · 14.1 KB
/
no-unnecessary-condition.test.ts
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
import {
TestCaseError,
InvalidTestCase,
} from '@typescript-eslint/experimental-utils/dist/ts-eslint';
import rule, {
Options,
MessageId,
} from '../../src/rules/no-unnecessary-condition';
import { RuleTester, getFixturesRootDir, noFormat } from '../RuleTester';
const rootPath = getFixturesRootDir();
const ruleTester = new RuleTester({
parser: '@typescript-eslint/parser',
parserOptions: {
tsconfigRootDir: rootPath,
project: './tsconfig.json',
},
});
const ruleError = (
line: number,
column: number,
messageId: MessageId,
): TestCaseError<MessageId> => ({
messageId,
line,
column,
});
const necessaryConditionTest = (condition: string): string => `
declare const b1: ${condition};
declare const b2: boolean;
const t1 = b1 && b2;
`;
const unnecessaryConditionTest = (
condition: string,
messageId: MessageId,
): InvalidTestCase<MessageId, Options> => ({
code: necessaryConditionTest(condition),
errors: [ruleError(4, 12, messageId)],
});
ruleTester.run('no-unnecessary-conditionals', rule, {
valid: [
`
declare const b1: boolean;
declare const b2: boolean;
const t1 = b1 && b2;
const t2 = b1 || b2;
if (b1 && b2) {
}
while (b1 && b2) {}
for (let i = 0; b1 && b2; i++) {
break;
}
const t1 = b1 && b2 ? 'yes' : 'no';
if (b1 && b2) {
}
while (b1 && b2) {}
for (let i = 0; b1 && b2; i++) {
break;
}
const t1 = b1 && b2 ? 'yes' : 'no';
for (;;) {}
`,
necessaryConditionTest('false | 5'), // Truthy literal and falsy literal
necessaryConditionTest('boolean | "foo"'), // boolean and truthy literal
necessaryConditionTest('0 | boolean'), // boolean and falsy literal
necessaryConditionTest('boolean | object'), // boolean and always-truthy type
necessaryConditionTest('false | object'), // always truthy type and falsy literal
// always falsy type and always truthy type
necessaryConditionTest('null | object'),
necessaryConditionTest('undefined | true'),
necessaryConditionTest('void | true'),
necessaryConditionTest('any'), // any
necessaryConditionTest('unknown'), // unknown
// Generic type params
`
function test<T extends string>(t: T) {
return t ? 'yes' : 'no';
}
`,
`
// Naked type param
function test<T>(t: T) {
return t ? 'yes' : 'no';
}
`,
`
// Naked type param in union
function test<T>(t: T | []) {
return t ? 'yes' : 'no';
}
`,
// Boolean expressions
`
function test(a: string) {
return a === 'a';
}
`,
`
function test(a?: string) {
const t1 = a === undefined;
const t3 = undefined === a;
}
`,
/**
* Predicate functions
**/
`
// with literal arrow function
[0, 1, 2].filter(x => x);
// filter with named function
function length(x: string) {
return x.length;
}
['a', 'b', ''].filter(length);
// with non-literal array
function nonEmptyStrings(x: string[]) {
return x.filter(length);
}
`,
// Ignores non-array methods of the same name
`
const notArray = {
filter: (func: () => boolean) => func(),
find: (func: () => boolean) => func(),
};
notArray.filter(() => true);
notArray.find(() => true);
`,
// Nullish coalescing operator
`
function test(a: string | null) {
return a ?? 'default';
}
`,
`
function test(a: string | undefined) {
return a ?? 'default';
}
`,
`
function test(a: string | null | undefined) {
return a ?? 'default';
}
`,
`
function test(a: unknown) {
return a ?? 'default';
}
`,
// Indexing cases
`
declare const arr: object[];
if (arr[42]) {
} // looks unnecessary from the types, but isn't
const tuple = [{}] as [object];
declare const n: number;
if (tuple[n]) {
}
`,
// Optional-chaining indexing
`
declare const arr: Array<{ value: string } & (() => void)>;
if (arr[42]?.value) {
}
arr[41]?.();
// An array access can "infect" deeper into the chain
declare const arr2: Array<{ x: { y: { z: object } } }>;
arr2[42]?.x?.y?.z;
const tuple = ['foo'] as const;
declare const n: number;
tuple[n]?.toUpperCase();
`,
`
if (arr?.[42]) {
}
`,
`
declare const returnsArr: undefined | (() => string[]);
if (returnsArr?.()[42]) {
}
returnsArr?.()[42]?.toUpperCase();
`,
// nullish + array index
`
declare const arr: string[][];
arr[x] ?? [];
`,
// Doesn't check the right-hand side of a logical expression
// in a non-conditional context
{
code: `
declare const b1: boolean;
declare const b2: true;
const x = b1 && b2;
`,
},
{
code: `
while (true) {}
for (; true; ) {}
do {} while (true);
`,
options: [{ allowConstantLoopConditions: true }],
},
`
let foo: undefined | { bar: true };
foo?.bar;
`,
`
let foo: null | { bar: true };
foo?.bar;
`,
`
let foo: undefined;
foo?.bar;
`,
`
let foo: undefined;
foo?.bar.baz;
`,
`
let foo: null;
foo?.bar;
`,
`
let anyValue: any;
anyValue?.foo;
`,
`
let unknownValue: unknown;
unknownValue?.foo;
`,
`
let foo: undefined | (() => {});
foo?.();
`,
`
let foo: null | (() => {});
foo?.();
`,
`
let foo: undefined;
foo?.();
`,
`
let foo: undefined;
foo?.().bar;
`,
`
let foo: null;
foo?.();
`,
`
let anyValue: any;
anyValue?.();
`,
`
let unknownValue: unknown;
unknownValue?.();
`,
'const foo = [1, 2, 3][0];',
],
invalid: [
// Ensure that it's checking in all the right places
{
code: `
const b1 = true;
declare const b2: boolean;
const t1 = b1 && b2;
const t2 = b1 || b2;
if (b1 && b2) {
}
if (b2 && b1) {
}
while (b1 && b2) {}
while (b2 && b1) {}
for (let i = 0; b1 && b2; i++) {
break;
}
const t1 = b1 && b2 ? 'yes' : 'no';
const t1 = b2 && b1 ? 'yes' : 'no';
`,
errors: [
ruleError(4, 12, 'alwaysTruthy'),
ruleError(5, 12, 'alwaysTruthy'),
ruleError(6, 5, 'alwaysTruthy'),
ruleError(8, 11, 'alwaysTruthy'),
ruleError(10, 8, 'alwaysTruthy'),
ruleError(11, 14, 'alwaysTruthy'),
ruleError(12, 17, 'alwaysTruthy'),
ruleError(15, 12, 'alwaysTruthy'),
ruleError(16, 18, 'alwaysTruthy'),
],
},
// Ensure that it's complaining about the right things
unnecessaryConditionTest('object', 'alwaysTruthy'),
unnecessaryConditionTest('object | true', 'alwaysTruthy'),
unnecessaryConditionTest('"" | false', 'alwaysFalsy'), // Two falsy literals
unnecessaryConditionTest('"always truthy"', 'alwaysTruthy'),
unnecessaryConditionTest(`undefined`, 'alwaysFalsy'),
unnecessaryConditionTest('null', 'alwaysFalsy'),
unnecessaryConditionTest('void', 'alwaysFalsy'),
unnecessaryConditionTest('never', 'never'),
// More complex logical expressions
{
code: `
declare const b1: boolean;
declare const b2: boolean;
if (true && b1 && b2) {
}
if (b1 && false && b2) {
}
if (b1 || b2 || true) {
}
`,
errors: [
ruleError(4, 5, 'alwaysTruthy'),
ruleError(6, 11, 'alwaysFalsy'),
ruleError(8, 17, 'alwaysTruthy'),
],
},
// Generic type params
{
code: `
function test<T extends object>(t: T) {
return t ? 'yes' : 'no';
}
`,
errors: [ruleError(3, 10, 'alwaysTruthy')],
},
{
code: `
function test<T extends false>(t: T) {
return t ? 'yes' : 'no';
}
`,
errors: [ruleError(3, 10, 'alwaysFalsy')],
},
{
code: `
function test<T extends 'a' | 'b'>(t: T) {
return t ? 'yes' : 'no';
}
`,
errors: [ruleError(3, 10, 'alwaysTruthy')],
},
// Boolean expressions
{
code: `
function test(a: 'a') {
return a === 'a';
}
`,
errors: [ruleError(3, 10, 'literalBooleanExpression')],
},
{
code: `
const y = 1;
if (y === 0) {
}
`,
errors: [ruleError(3, 5, 'literalBooleanExpression')],
},
{
code: `
enum Foo {
a = 1,
b = 2,
}
const x = Foo.a;
if (x === Foo.a) {
}
`,
errors: [ruleError(8, 5, 'literalBooleanExpression')],
},
// Workaround https://github.com/microsoft/TypeScript/issues/37160
{
code: `
function test(a: string) {
const t1 = a !== undefined;
const t3 = undefined === a;
}
`,
errors: [
ruleError(3, 14, 'noOverlapBooleanExpression'),
ruleError(4, 14, 'noOverlapBooleanExpression'),
],
},
{
code: `
function test(a?: string) {
const t1 = a === null;
const t3 = null !== a;
}
`,
errors: [
ruleError(3, 14, 'noOverlapBooleanExpression'),
ruleError(4, 14, 'noOverlapBooleanExpression'),
],
},
// Nullish coalescing operator
{
code: `
function test(a: string) {
return a ?? 'default';
}
`,
errors: [ruleError(3, 10, 'neverNullish')],
},
{
code: `
function test(a: string | false) {
return a ?? 'default';
}
`,
errors: [ruleError(3, 10, 'neverNullish')],
},
{
code: `
function test(a: null) {
return a ?? 'default';
}
`,
errors: [ruleError(3, 10, 'alwaysNullish')],
},
{
code: `
function test(a: never) {
return a ?? 'default';
}
`,
errors: [ruleError(3, 10, 'never')],
},
// Predicate functions
{
code: `
[1, 3, 5].filter(() => true);
[1, 2, 3].find(() => {
return false;
});
// with non-literal array
function nothing(x: string[]) {
return x.filter(() => false);
}
// with readonly array
function nothing2(x: readonly string[]) {
return x.filter(() => false);
}
// with tuple
function nothing3(x: [string, string]) {
return x.filter(() => false);
}
`,
errors: [
ruleError(2, 24, 'alwaysTruthy'),
ruleError(4, 10, 'alwaysFalsy'),
ruleError(9, 25, 'alwaysFalsy'),
ruleError(13, 25, 'alwaysFalsy'),
ruleError(17, 25, 'alwaysFalsy'),
],
},
// Indexing cases
{
// This is an error because 'dict' doesn't represent
// the potential for undefined in its types
code: `
declare const dict: Record<string, object>;
if (dict['mightNotExist']) {
}
`,
errors: [ruleError(3, 5, 'alwaysTruthy')],
},
{
// Should still check tuples when accessed with literal numbers, since they don't have
// unsound index signatures
code: `
const x = [{}] as [{ foo: string }];
if (x[0]) {
}
if (x[0]?.foo) {
}
`,
errors: [
ruleError(3, 5, 'alwaysTruthy'),
ruleError(5, 9, 'neverOptionalChain'),
],
},
{
// Shouldn't mistake this for an array indexing case
code: `
declare const arr: object[];
if (arr.filter) {
}
`,
errors: [ruleError(3, 5, 'alwaysTruthy')],
},
{
code: `
function truthy() {
return [];
}
function falsy() {}
[1, 3, 5].filter(truthy);
[1, 2, 3].find(falsy);
`,
errors: [
ruleError(6, 18, 'alwaysTruthyFunc'),
ruleError(7, 16, 'alwaysFalsyFunc'),
],
},
// Supports generics
// TODO: fix this
// {
// code: `
// const isTruthy = <T>(t: T) => T;
// // Valid: numbers can be truthy or falsy (0).
// [0,1,2,3].filter(isTruthy);
// // Invalid: arrays are always falsy.
// [[1,2], [3,4]].filter(isTruthy);
// `,
// errors: [ruleError(6, 23, 'alwaysTruthyFunc')],
// },
{
code: `
while (true) {}
for (; true; ) {}
do {} while (true);
`,
options: [{ allowConstantLoopConditions: false }],
errors: [
ruleError(2, 8, 'alwaysTruthy'),
ruleError(3, 8, 'alwaysTruthy'),
ruleError(4, 14, 'alwaysTruthy'),
],
},
{
code: noFormat`
let foo = { bar: true };
foo?.bar;
foo ?. bar;
foo ?.
bar;
foo
?. bar;
`,
output: noFormat`
let foo = { bar: true };
foo.bar;
foo . bar;
foo .
bar;
foo
. bar;
`,
errors: [
{
messageId: 'neverOptionalChain',
line: 3,
column: 4,
endLine: 3,
endColumn: 6,
},
{
messageId: 'neverOptionalChain',
line: 4,
column: 5,
endLine: 4,
endColumn: 7,
},
{
messageId: 'neverOptionalChain',
line: 5,
column: 5,
endLine: 5,
endColumn: 7,
},
{
messageId: 'neverOptionalChain',
line: 8,
column: 3,
endLine: 8,
endColumn: 5,
},
],
},
{
code: noFormat`
let foo = () => {};
foo?.();
foo ?. ();
foo ?.
();
foo
?. ();
`,
output: `
let foo = () => {};
foo();
foo ();
foo${' '}
();
foo
();
`,
errors: [
{
messageId: 'neverOptionalChain',
line: 3,
column: 4,
endLine: 3,
endColumn: 6,
},
{
messageId: 'neverOptionalChain',
line: 4,
column: 5,
endLine: 4,
endColumn: 7,
},
{
messageId: 'neverOptionalChain',
line: 5,
column: 5,
endLine: 5,
endColumn: 7,
},
{
messageId: 'neverOptionalChain',
line: 8,
column: 3,
endLine: 8,
endColumn: 5,
},
],
},
{
code: noFormat`
let foo = () => {};
foo?.(bar);
foo ?. (bar);
foo ?.
(bar);
foo
?. (bar);
`,
output: `
let foo = () => {};
foo(bar);
foo (bar);
foo${' '}
(bar);
foo
(bar);
`,
errors: [
{
messageId: 'neverOptionalChain',
line: 3,
column: 4,
endLine: 3,
endColumn: 6,
},
{
messageId: 'neverOptionalChain',
line: 4,
column: 5,
endLine: 4,
endColumn: 7,
},
{
messageId: 'neverOptionalChain',
line: 5,
column: 5,
endLine: 5,
endColumn: 7,
},
{
messageId: 'neverOptionalChain',
line: 8,
column: 3,
endLine: 8,
endColumn: 5,
},
],
},
{
code: 'const foo = [1, 2, 3]?.[0];',
output: 'const foo = [1, 2, 3][0];',
errors: [
{
messageId: 'neverOptionalChain',
line: 1,
endLine: 1,
column: 22,
endColumn: 24,
},
],
},
],
});