eslint-plugin-aliased-props
Version:
An ESLint plugin to enforce aliased (named) types for React component props.
75 lines (64 loc) • 1.78 kB
JavaScript
/**
* @fileoverview Require React component props to have an aliased (named) type.
*/
;
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: 'Require React component props to have an aliased (named) type.',
category: 'Best Practices',
recommended: false,
},
fixable: null, // or 'code' if you implement autofix
schema: [], // No options
},
create(context) {
const ts = require('@typescript-eslint/typescript-estree');
return {
FunctionDeclaration(node) {
checkPropsParameter(node);
},
ArrowFunctionExpression(node) {
if (node.parent && node.parent.type === 'VariableDeclarator') {
checkPropsParameter(node);
}
},
};
function checkPropsParameter(node) {
const isReactComponent = isNodeReactComponent(node);
if (!isReactComponent) {
return;
}
const firstParam = node.params[0];
if (!firstParam || firstParam.type !== 'Identifier') {
return;
}
const typeAnnotation = firstParam.typeAnnotation;
if (
typeAnnotation &&
typeAnnotation.typeAnnotation &&
typeAnnotation.typeAnnotation.type === 'TSTypeLiteral'
) {
context.report({
node: typeAnnotation,
message:
'Props should use a named interface or type alias instead of an inline type.',
});
}
}
function isNodeReactComponent(node) {
// Check if the function returns JSX
let hasJSX = false;
context.getSourceCode().traverse(node.body, {
JSXElement() {
hasJSX = true;
},
JSXFragment() {
hasJSX = true;
},
});
return hasJSX;
}
},
};