1
1
import type { TSESLint , TSESTree } from '@typescript-eslint/utils' ;
2
2
import { AST_NODE_TYPES , AST_TOKEN_TYPES } from '@typescript-eslint/utils' ;
3
+ import * as tsutils from 'tsutils' ;
3
4
import * as ts from 'typescript' ;
4
5
5
6
import * as util from '../util' ;
@@ -9,13 +10,15 @@ export type Options = [
9
10
ignoreConditionalTests ?: boolean ;
10
11
ignoreTernaryTests ?: boolean ;
11
12
ignoreMixedLogicalExpressions ?: boolean ;
13
+ allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing ?: boolean ;
12
14
} ,
13
15
] ;
14
16
15
17
export type MessageIds =
16
18
| 'preferNullishOverOr'
17
19
| 'preferNullishOverTernary'
18
- | 'suggestNullish' ;
20
+ | 'suggestNullish'
21
+ | 'noStrictNullCheck' ;
19
22
20
23
export default util . createRule < Options , MessageIds > ( {
21
24
name : 'prefer-nullish-coalescing' ,
@@ -34,6 +37,8 @@ export default util.createRule<Options, MessageIds>({
34
37
preferNullishOverTernary :
35
38
'Prefer using nullish coalescing operator (`??`) instead of a ternary expression, as it is simpler to read.' ,
36
39
suggestNullish : 'Fix to nullish coalescing operator (`??`).' ,
40
+ noStrictNullCheck :
41
+ 'This rule requires the `strictNullChecks` compiler option to be turned on to function correctly.' ,
37
42
} ,
38
43
schema : [
39
44
{
@@ -48,6 +53,9 @@ export default util.createRule<Options, MessageIds>({
48
53
ignoreMixedLogicalExpressions : {
49
54
type : 'boolean' ,
50
55
} ,
56
+ allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing : {
57
+ type : 'boolean' ,
58
+ } ,
51
59
} ,
52
60
additionalProperties : false ,
53
61
} ,
@@ -58,6 +66,7 @@ export default util.createRule<Options, MessageIds>({
58
66
ignoreConditionalTests : true ,
59
67
ignoreTernaryTests : true ,
60
68
ignoreMixedLogicalExpressions : true ,
69
+ allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing : false ,
61
70
} ,
62
71
] ,
63
72
create (
@@ -67,12 +76,31 @@ export default util.createRule<Options, MessageIds>({
67
76
ignoreConditionalTests,
68
77
ignoreTernaryTests,
69
78
ignoreMixedLogicalExpressions,
79
+ allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing,
70
80
} ,
71
81
] ,
72
82
) {
73
83
const parserServices = util . getParserServices ( context ) ;
84
+ const compilerOptions = parserServices . program . getCompilerOptions ( ) ;
74
85
const sourceCode = context . getSourceCode ( ) ;
75
86
const checker = parserServices . program . getTypeChecker ( ) ;
87
+ const isStrictNullChecks = tsutils . isStrictCompilerOptionEnabled (
88
+ compilerOptions ,
89
+ 'strictNullChecks' ,
90
+ ) ;
91
+
92
+ if (
93
+ ! isStrictNullChecks &&
94
+ allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing !== true
95
+ ) {
96
+ context . report ( {
97
+ loc : {
98
+ start : { line : 0 , column : 0 } ,
99
+ end : { line : 0 , column : 0 } ,
100
+ } ,
101
+ messageId : 'noStrictNullCheck' ,
102
+ } ) ;
103
+ }
76
104
77
105
return {
78
106
ConditionalExpression ( node : TSESTree . ConditionalExpression ) : void {
0 commit comments