UNPKG

1.36 kBJavaScriptView Raw
1const Components = require('eslint-plugin-react/lib/util/Components');
2
3const {docsUrl, getName} = require('../utilities');
4
5module.exports = {
6 meta: {
7 docs: {
8 description: 'Require that React component state be typed in TypeScript.',
9 category: 'Possible Errors',
10 recommended: true,
11 uri: docsUrl('react-type-state'),
12 },
13 schema: [],
14 },
15
16 create: Components.detect((context, components, utils) => {
17 let inTypeScriptReactComponent = false;
18
19 function looksLikeTypeScriptComponent(node) {
20 return (
21 utils.isES6Component(node) &&
22 Boolean(node.superTypeParameters) &&
23 Boolean(node.superTypeParameters.params) &&
24 node.superTypeParameters.params.length > 0 &&
25 node.superTypeParameters.params[0].type === 'TSTypeReference'
26 );
27 }
28
29 return {
30 ClassDeclaration(node) {
31 inTypeScriptReactComponent = looksLikeTypeScriptComponent(node);
32 },
33 ClassProperty(node) {
34 if (
35 !inTypeScriptReactComponent ||
36 getName(node.key) !== 'state' ||
37 node.typeAnnotation != null
38 ) {
39 return;
40 }
41
42 context.report(
43 node,
44 'Add the type of the state instance property so that it matches the second type parameter of your React component.',
45 );
46 },
47 };
48 }),
49};