Skip to content

Commit

Permalink
fix(no-unsafe-references): Ignore TypeScript type references
Browse files Browse the repository at this point in the history
Fixes #214
  • Loading branch information
mskelton committed Feb 16, 2024
1 parent afa013f commit 3b3cafd
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/rules/no-unsafe-references.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { AST, Rule, Scope } from 'eslint';
import * as ESTree from 'estree';
import { getStringValue, isFunction, isPageMethod } from '../utils/ast';
import {
getParent,
getStringValue,
isFunction,
isPageMethod,
} from '../utils/ast';
import { truthy } from '../utils/misc';

/** Collect all variable references in the parent scopes recursively. */
Expand Down Expand Up @@ -101,6 +106,10 @@ export default {
// If a variable is used in the function, but not declared in the parent,
// then it's likely a global variable such as `Promise` or `console`.
through
.filter((ref) => {
const parent = getParent(ref.identifier);
return (parent?.type as string) !== 'TSTypeReference';
})
.filter((ref) => allRefs.has(ref.identifier.name))
.forEach((ref, i, arr) => {
const descriptor: Rule.ReportDescriptor = {
Expand Down
4 changes: 4 additions & 0 deletions src/utils/ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,10 @@ export function isDescribeCall(node: ESTree.Node): boolean {
: false;
}

export function getParent(node: ESTree.Node): ESTree.Node | undefined {
return (node as any).parent;
}

export function findParent<T extends ESTree.Node['type']>(
node: NodeWithParent,
type: T,
Expand Down
34 changes: 34 additions & 0 deletions test/spec/no-unsafe-references.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -316,5 +316,39 @@ runRuleTester('no-unsafe-references', rule, {
`,
name: 'Multi-level scopes',
},
// TypeScript
{
code: dedent`
type X = number;
const result = await page.evaluate(() => {
const x = 10 as X;
return Promise.resolve(x);
});
`,
name: 'TypeScript - variable assignment of type',
parser: require.resolve('@typescript-eslint/parser'),
},
{
code: dedent`
type X = number;
const result = await page.evaluate(() => {
const foo = (bar: X) => bar;
return Promise.resolve(foo(10));
});
`,
name: 'TypeScript - parameter type',
parser: require.resolve('@typescript-eslint/parser'),
},
{
code: dedent`
type X = number;
const result = await page.evaluate(() => {
const x: X = 10;
return Promise.resolve(x);
});
`,
name: 'TypeScript - casting',
parser: require.resolve('@typescript-eslint/parser'),
},
],
});

0 comments on commit 3b3cafd

Please sign in to comment.