/
no-object-literal-type-assertion.ts
92 lines (88 loc) · 2.25 KB
/
no-object-literal-type-assertion.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
import {
AST_NODE_TYPES,
TSESTree,
} from '@typescript-eslint/experimental-utils';
import * as util from '../util';
type Options = [
{
allowAsParameter?: boolean;
}
];
type MessageIds = 'unexpectedTypeAssertion';
export default util.createRule<Options, MessageIds>({
name: 'no-object-literal-type-assertion',
meta: {
type: 'problem',
docs: {
description:
'Forbids an object literal to appear in a type assertion expression',
tslintRuleName: 'no-object-literal-type-assertion',
category: 'Stylistic Issues',
recommended: 'error',
},
messages: {
unexpectedTypeAssertion:
'Type assertion on object literals is forbidden, use a type annotation instead.',
},
schema: [
{
type: 'object',
additionalProperties: false,
properties: {
allowAsParameter: {
type: 'boolean',
},
},
},
],
},
defaultOptions: [
{
allowAsParameter: false,
},
],
create(context, [{ allowAsParameter }]) {
/**
* Check whatever node should be reported
* @param node the node to be evaluated.
*/
function checkType(node: TSESTree.TypeNode): boolean {
switch (node.type) {
case AST_NODE_TYPES.TSAnyKeyword:
case AST_NODE_TYPES.TSUnknownKeyword:
return false;
case AST_NODE_TYPES.TSTypeReference:
// Ignore `as const` and `<const>` (#166)
return (
node.typeName.type === AST_NODE_TYPES.Identifier &&
node.typeName.name !== 'const'
);
default:
return true;
}
}
return {
'TSTypeAssertion, TSAsExpression'(
node: TSESTree.TSTypeAssertion | TSESTree.TSAsExpression,
) {
if (
allowAsParameter &&
node.parent &&
(node.parent.type === AST_NODE_TYPES.NewExpression ||
node.parent.type === AST_NODE_TYPES.CallExpression)
) {
return;
}
if (
checkType(node.typeAnnotation) &&
node.expression.type === AST_NODE_TYPES.ObjectExpression
) {
context.report({
node,
messageId: 'unexpectedTypeAssertion',
});
}
},
};
},
});