-
Notifications
You must be signed in to change notification settings - Fork 498
/
Copy pathenforce-optional-properties-last.ts
89 lines (75 loc) · 2.87 KB
/
enforce-optional-properties-last.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
// Copyright 2024 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview Rule to enforce that within TypeScript Types, optional properties should come last.
* This is to avoid a bug where clang-format will incorrectly indent a type that's failing this.
* @author Paul Irish
*/
import type {TSESTree} from '@typescript-eslint/utils';
import {createRule} from './utils/ruleCreator.ts';
// Define the message IDs used by the rule.
type MessageIds = 'optionalPropertyBeforeRequired';
// Define the structure of the options expected by the rule (none in this case).
type RuleOptions = [];
export default createRule<RuleOptions, MessageIds>({
name: 'enforce-optional-properties-last',
meta: {
type: 'problem',
docs: {
description: 'Enforce optional properties to be defined after required properties',
category: 'Possible Errors',
},
fixable: 'code',
messages: {
optionalPropertyBeforeRequired: 'Optional property \'{{name}}\' should be defined after required properties.',
},
schema: [],
},
defaultOptions: [],
create: function(context) {
const sourceCode = context.sourceCode;
return {
TSTypeAliasDeclaration(node) {
const typeAnnotation = node.typeAnnotation;
if (typeAnnotation.type !== 'TSTypeLiteral') {
return;
}
let misplacedOptionalProp: TSESTree.TSPropertySignature|null = null;
for (const member of typeAnnotation.members) {
// We only care about TSPropertySignature members (key: type)
if (member.type !== 'TSPropertySignature') {
continue;
}
// Ensure the key is an Identifier for safe name access
if (member.key.type !== 'Identifier') {
continue;
}
if (member.optional) {
misplacedOptionalProp = member;
} else if (misplacedOptionalProp) {
// Required property found after an optional one
const requiredProp = member;
const misplacedNode = misplacedOptionalProp;
context.report({
node: misplacedNode,
messageId: 'optionalPropertyBeforeRequired',
data: {
name: 'name' in misplacedNode.key ? misplacedNode.key.name : 'unknown',
},
fix(fixer) {
const optionalPropertyText = sourceCode.getText(misplacedNode);
const requiredPropertyText = sourceCode.getText(requiredProp);
// Swap the positions of the two properties
return [
fixer.replaceText(misplacedNode, requiredPropertyText),
fixer.replaceText(requiredProp, optionalPropertyText),
];
},
});
}
}
},
};
},
});