Skip to content

Instantly share code, notes, and snippets.

@mathieutu
Created March 10, 2022 14:20
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mathieutu/577be7f0cbeba71a894981f07fc082e3 to your computer and use it in GitHub Desktop.
Enforces never using React.ReactNode as the typing is wrong.
const MODULE = "common/types/react";
module.exports = {
meta: {
type: "problem",
docs: {
url:
"https://changelog.com/posts/the-react-reactnode-type-is-a-black-hole",
description: `Enforces never using React.ReactNode as the typing is wrong.`,
category: "react",
recommended: true,
},
fixable: "code",
messages: {
noUse: `React.ReactNode is considered unsafe. Use StrictReactNode from \`${MODULE}\` instead.`,
},
},
create({ report }) {
let alreadyImported = false;
return {
ImportDeclaration(node) {
if (
node.source.value === MODULE &&
node.specifiers.find(
(specifier) => specifier.imported.name === "StrictReactNode"
)
) {
alreadyImported = true;
}
},
TSTypeReference(node) {
if (
(node.typeName.type === "TSQualifiedName" &&
node.typeName.left.name === "React" &&
node.typeName.right.name === "ReactNode") ||
(node.typeName.type === "Identifier" &&
node.typeName.name === "ReactNode")
) {
report({
node,
messageId: "noUse",
fix: (fixer) => {
const fixers = [fixer.replaceText(node, "StrictReactNode")];
if (!alreadyImported) {
fixers.push(
fixer.insertTextBeforeRange(
[0, 0],
`import { StrictReactNode } from "${MODULE}";\n`
)
);
alreadyImported = true;
}
return fixers;
},
});
}
},
};
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment