Skip to content

Commit 8ffb56a

Browse files
feat(no-misused-observables): variable declarations
1 parent f442dbd commit 8ffb56a

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

src/rules/no-misused-observables.ts

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ export const noMisusedObservablesRule = ruleCreator({
6565
Property: checkProperty,
6666
ReturnStatement: checkReturnStatement,
6767
AssignmentExpression: checkAssignment,
68-
// VariableDeclarator: checkVariableDeclarator,
68+
VariableDeclarator: checkVariableDeclaration,
6969
};
7070

7171
const spreadChecks: eslint.RuleListener = {
@@ -237,6 +237,34 @@ export const noMisusedObservablesRule = ruleCreator({
237237
}
238238
}
239239

240+
function checkVariableDeclaration(node: es.VariableDeclarator): void {
241+
const tsNode = esTreeNodeToTSNodeMap.get(node);
242+
if (
243+
tsNode.initializer === undefined
244+
|| !node.init
245+
|| !node.id.typeAnnotation
246+
) {
247+
return;
248+
}
249+
250+
// Optimization to avoid touching type info.
251+
if (!isPossiblyFunctionType(node.id.typeAnnotation)) {
252+
return;
253+
}
254+
255+
const varType = getTypeAtLocation(node.id);
256+
if (!isVoidReturningFunctionType(varType)) {
257+
return;
258+
}
259+
260+
if (couldReturnObservable(node.init)) {
261+
context.report({
262+
messageId: 'forbiddenVoidReturnVariable',
263+
node: node.init,
264+
});
265+
}
266+
}
267+
240268
return {
241269
...(checksVoidReturn ? voidReturnChecks : {}),
242270
...(checksSpreads ? spreadChecks : {}),

tests/rules/no-misused-observables.test.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,7 @@ ruleTester({ types: true }).run('no-misused-observables', noMisusedObservablesRu
213213
214214
let foo: () => void;
215215
foo = (): Observable<number> => of(42);
216+
const bar: () => void = (): Observable<number> => of(42);
216217
`,
217218
options: [{ checksVoidReturn: false }],
218219
},
@@ -756,6 +757,17 @@ ruleTester({ types: true }).run('no-misused-observables', noMisusedObservablesRu
756757
~~~~~~~~~~~~ [forbiddenVoidReturnVariable]
757758
`,
758759
),
760+
fromFixture(
761+
stripIndent`
762+
// void return variable; const
763+
import { of } from "rxjs";
764+
765+
const foo: () => void = () => of(42);
766+
~~~~~~~~~~~~ [forbiddenVoidReturnVariable]
767+
const bar = () => of(42), baz: () => void = () => of(42);
768+
~~~~~~~~~~~~ [forbiddenVoidReturnVariable]
769+
`,
770+
),
759771
fromFixture(
760772
stripIndent`
761773
// void return variable; nested

0 commit comments

Comments
 (0)