Skip to content

Commit

Permalink
feat(eslint): add rule no-optional-inputs
Browse files Browse the repository at this point in the history
  • Loading branch information
dhhyi committed Apr 15, 2022
1 parent 2a6457f commit bef468b
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
40 changes: 40 additions & 0 deletions eslint-rules/src/rules/no-optional-inputs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { Selectors } from '@angular-eslint/utils';
import { AST_NODE_TYPES, TSESLint, TSESTree } from '@typescript-eslint/utils';

const messages = {
doNotUseOptionalOperatorOnInputs: 'Angular @Input() properties are optional by default.',
};

const noOptionalInputsRule: TSESLint.RuleModule<keyof typeof messages> = {
meta: {
messages,
type: 'problem',
fixable: 'code',
schema: [],
docs: {
description: 'Disallow optional inputs',
recommended: 'warn',
},
},
create: context => ({
[Selectors.INPUT_DECORATOR](node: TSESTree.Decorator): void {
if (
node.parent.type === AST_NODE_TYPES.PropertyDefinition &&
node.parent.key.type === AST_NODE_TYPES.Identifier &&
node.parent.key.parent.type === AST_NODE_TYPES.PropertyDefinition &&
node.parent.key.parent.optional
) {
const loc = node.parent.key.range[1];
context.report({
node: node.parent.key.parent,
messageId: 'doNotUseOptionalOperatorOnInputs',
fix(fixer) {
return fixer.removeRange([loc, loc + 1]);
},
});
}
},
}),
};

export default noOptionalInputsRule;
24 changes: 24 additions & 0 deletions eslint-rules/tests/no-optional-inputs.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import noOptionalInputsRule from '../src/rules/no-optional-inputs';

import testRule from './rule-tester';

testRule(noOptionalInputsRule, {
valid: [
{
name: 'should not report when inputs do not use the optional operator',
code: 'export class MyComponent { @Input() foo: string; }',
},
],
invalid: [
{
name: 'should report when inputs use the optional operator',
code: 'export class MyComponent { @Input() foo?: string; }',
errors: [
{
messageId: 'doNotUseOptionalOperatorOnInputs',
},
],
output: 'export class MyComponent { @Input() foo: string; }',
},
],
});

0 comments on commit bef468b

Please sign in to comment.