-
Notifications
You must be signed in to change notification settings - Fork 683
Expand file tree
/
Copy pathno-null.ts
More file actions
74 lines (67 loc) · 2.81 KB
/
no-null.ts
File metadata and controls
74 lines (67 loc) · 2.81 KB
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
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import type { TSESTree, TSESLint } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
type MessageIds = 'error-usage-of-null';
type Options = [];
const noNullRule: TSESLint.RuleModule<MessageIds, Options> = {
defaultOptions: [],
meta: {
type: 'problem',
messages: {
'error-usage-of-null':
'Usage of "null" is deprecated except when received from legacy APIs; use "undefined" instead'
},
schema: [],
docs: {
description: 'Prevent usage of JavaScript\'s "null" keyword',
recommended: 'recommended',
url: 'https://www.npmjs.com/package/@rushstack/eslint-plugin'
} as TSESLint.RuleMetaDataDocs
},
create: (context: TSESLint.RuleContext<MessageIds, Options>) => {
return {
Literal: function (node: TSESTree.Literal) {
// Is it a "null" literal?
if (node.value === null) {
// Does the "null" appear in a comparison such as "if (x === null)"?
if (node.parent && node.parent.type === AST_NODE_TYPES.BinaryExpression) {
const operator: string = node.parent.operator;
if (operator === '!==' || operator === '===' || operator === '!=' || operator === '==') {
return;
}
}
// Is this "Object.create(null)"? This is the correct pattern for creating
// a dictionary object that does not inherit members from the Object prototype.
if (
node.parent &&
node.parent.type === AST_NODE_TYPES.CallExpression &&
node.parent.arguments[0] === node &&
node.parent.callee.type === AST_NODE_TYPES.MemberExpression &&
node.parent.callee.object.type === AST_NODE_TYPES.Identifier &&
node.parent.callee.object.name === 'Object' &&
node.parent.callee.property.type === AST_NODE_TYPES.Identifier &&
node.parent.callee.property.name === 'create'
) {
return;
}
// Is this "__proto__: null" inside an object literal? This is used to create
// an object literal that does not inherit from Object.prototype.
if (
node.parent &&
node.parent.type === AST_NODE_TYPES.Property &&
!node.parent.computed &&
((node.parent.key.type === AST_NODE_TYPES.Identifier &&
node.parent.key.name === '__proto__') ||
(node.parent.key.type === AST_NODE_TYPES.Literal &&
node.parent.key.value === '__proto__'))
) {
return;
}
context.report({ node, messageId: 'error-usage-of-null' });
}
}
};
}
};
export { noNullRule };