@@ -36,6 +36,9 @@ function create(context) {
36
36
const constructor = clazz . body . body . find ( node => node . kind === 'constructor' && node . value . type === 'FunctionExpression' ) ??
37
37
clazz . body . body . find ( node => node . kind === 'constructor' ) ;
38
38
// MethodDefinition > FunctionExpression > BlockStatement > []
39
+ const isReact = clazz . superClass ?. name === 'Component'
40
+ || ( clazz . superClass ?. object ?. name === 'React' && clazz . superClass ?. property . name === 'Component' ) ;
41
+ const unsupportedSuper = ! isReact && ! ! clazz . superClass ;
39
42
const isMakeObservable = node => node . expression ?. callee ?. name === 'makeObservable' && node . expression ?. arguments [ 0 ] ?. type === 'ThisExpression' ;
40
43
const makeObservable = constructor ?. value . body ?. body . find ( isMakeObservable ) ?. expression ;
41
44
@@ -50,6 +53,10 @@ function create(context) {
50
53
}
51
54
} else {
52
55
const fix = fixer => {
56
+ // The class extends a another unknown class so we can not safely create a super call.
57
+ if ( unsupportedSuper && ! constructor ) {
58
+ return ;
59
+ }
53
60
54
61
const fixes = [ ] ;
55
62
let makeObservableExpr = 'makeObservable' ;
@@ -71,7 +78,15 @@ function create(context) {
71
78
// constructor() {}
72
79
const closingBracket = sourceCode . getLastToken ( constructor . value . body ) ;
73
80
fixes . push ( fixer . insertTextBefore ( closingBracket , `;${ makeObservableExpr } (this);` ) ) ;
74
- } else {
81
+ } else if ( isReact ) {
82
+ // class C extends Component<{ foo: string }> {}
83
+ let propsType = '' ;
84
+ if ( clazz . superTypeParameters ?. params . length ) {
85
+ propsType = `: ${ sourceCode . getText ( clazz . superTypeParameters . params [ 0 ] ) } ` ;
86
+ }
87
+ const openingBracket = sourceCode . getFirstToken ( clazz . body ) ;
88
+ fixes . push ( fixer . insertTextAfter ( openingBracket , `\nconstructor(props${ propsType } ) { super(props); ${ makeObservableExpr } (this); }` ) ) ;
89
+ } else if ( ! unsupportedSuper ) {
75
90
// class C {}
76
91
const openingBracket = sourceCode . getFirstToken ( clazz . body ) ;
77
92
fixes . push ( fixer . insertTextAfter ( openingBracket , `\nconstructor() { ${ makeObservableExpr } (this); }` ) ) ;
@@ -82,7 +97,7 @@ function create(context) {
82
97
83
98
context . report ( {
84
99
node : clazz ,
85
- messageId : 'missingMakeObservable' ,
100
+ messageId : unsupportedSuper ? 'missingMakeObservableSuper' : 'missingMakeObservable' ,
86
101
fix,
87
102
} )
88
103
}
@@ -101,6 +116,7 @@ module.exports = {
101
116
} ,
102
117
messages : {
103
118
missingMakeObservable : "Constructor is missing `makeObservable(this)`." ,
119
+ missingMakeObservableSuper : "Constructor is missing `makeObservable(this)`. Can not fix because of missing super call." ,
104
120
secondArgMustBeNullish : "`makeObservable`'s second argument must be nullish or not provided when using decorators."
105
121
} ,
106
122
} ,
0 commit comments