Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(eslint-plugin): [ban-types] allow banning null and undefined #821

Merged
merged 10 commits into from Feb 12, 2020
70 changes: 54 additions & 16 deletions packages/eslint-plugin/src/rules/ban-types.ts
Expand Up @@ -41,6 +41,51 @@ function getCustomMessage(
return '';
}

function reportBannedType(
Validark marked this conversation as resolved.
Show resolved Hide resolved
node: TSESTree.EntityName | TSESTree.TSNullKeyword,
name: string,
context: TSESLint.RuleContext<
'bannedTypeMessage',
[
{
types: Record<
string,
| string
| {
message: string;
fixWith?: string | undefined;
}
| null
>;
}
]
>,
bannedTypes: Record<
string,
| string
| {
message: string;
fixWith?: string | undefined;
}
| null
>,
) {
const bannedType = bannedTypes[name];
const customMessage = getCustomMessage(bannedType);
const fixWith =
bannedType && typeof bannedType === 'object' && bannedType.fixWith;

context.report({
node: node,
messageId: 'bannedTypeMessage',
data: {
name,
customMessage,
},
fix: fixWith ? fixer => fixer.replaceText(node, fixWith) : null,
});
}

export default util.createRule<Options, MessageIds>({
name: 'ban-types',
meta: {
Expand Down Expand Up @@ -107,27 +152,20 @@ export default util.createRule<Options, MessageIds>({
},
],
create(context, [{ types: bannedTypes }]) {
return {
const ruleListener: TSESLint.RuleListener = {
TSTypeReference({ typeName }) {
const name = stringifyTypeName(typeName, context.getSourceCode());

if (name in bannedTypes) {
const bannedType = bannedTypes[name];
const customMessage = getCustomMessage(bannedType);
const fixWith =
bannedType && typeof bannedType === 'object' && bannedType.fixWith;

context.report({
node: typeName,
messageId: 'bannedTypeMessage',
data: {
name: name,
customMessage,
},
fix: fixWith ? fixer => fixer.replaceText(typeName, fixWith) : null,
});
reportBannedType(typeName, name, context, bannedTypes);
}
},
};

if ('null' in bannedTypes) {
ruleListener.TSNullKeyword = typeName => {
reportBannedType(typeName, 'null', context, bannedTypes);
};
}
return ruleListener;
},
});