Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(eslint-plugin): add no-unsafe-declaration-merging #5840

Merged
merged 5 commits into from Oct 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
54 changes: 54 additions & 0 deletions packages/eslint-plugin/docs/rules/no-unsafe-declaration-merging.md
@@ -0,0 +1,54 @@
---
description: 'Disallow unsafe declaration merging.'
---

> 🛑 This file is source code, not the primary documentation location! 🛑
>
> See **https://typescript-eslint.io/rules/no-unsafe-declaration-merging** for documentation.

TypeScript's "declaration merging" supports merging separate declarations with the same name.

Declaration merging between classes and interfaces is unsafe.
The TypeScript compiler doesn't check whether properties are initialized, which can cause lead to TypeScript not detecting code that will cause runtime errors.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oops typo!

Suggested change
The TypeScript compiler doesn't check whether properties are initialized, which can cause lead to TypeScript not detecting code that will cause runtime errors.
The TypeScript compiler doesn't check whether properties are initialized, which can lead to TypeScript not detecting code that will cause runtime errors.


```ts
interface Foo {
nums: number[];
}

class Foo {}

const foo = new Foo();

foo.nums.push(1); // Runtime Error: Cannot read properties of undefined.
```

## Examples

<!--tabs-->

### ❌ Incorrect

```ts
interface Foo {}

class Foo {}
```

### ✅ Correct

```ts
interface Foo {}
class Bar implements Foo {}

namespace Baz {}
namespace Baz {}
enum Baz {}

namespace Qux {}
function Qux() {}
```

## Further Reading

- [Declaration Merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html)
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/configs/all.ts
Expand Up @@ -108,6 +108,7 @@ export = {
'@typescript-eslint/no-unsafe-argument': 'error',
'@typescript-eslint/no-unsafe-assignment': 'error',
'@typescript-eslint/no-unsafe-call': 'error',
'@typescript-eslint/no-unsafe-declaration-merging': 'error',
'@typescript-eslint/no-unsafe-member-access': 'error',
'@typescript-eslint/no-unsafe-return': 'error',
'no-unused-expressions': 'off',
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/configs/strict.ts
Expand Up @@ -27,6 +27,7 @@ export = {
'@typescript-eslint/no-unnecessary-boolean-literal-compare': 'warn',
'@typescript-eslint/no-unnecessary-condition': 'warn',
'@typescript-eslint/no-unnecessary-type-arguments': 'warn',
'@typescript-eslint/no-unsafe-declaration-merging': 'warn',
'no-useless-constructor': 'off',
'@typescript-eslint/no-useless-constructor': 'warn',
'@typescript-eslint/non-nullable-type-assertion-style': 'warn',
Expand Down
2 changes: 2 additions & 0 deletions packages/eslint-plugin/src/rules/index.ts
Expand Up @@ -78,6 +78,7 @@ import noUnnecessaryTypeConstraint from './no-unnecessary-type-constraint';
import noUnsafeArgument from './no-unsafe-argument';
import noUnsafeAssignment from './no-unsafe-assignment';
import noUnsafeCall from './no-unsafe-call';
import noUnsafeDeclarationMerging from './no-unsafe-declaration-merging';
import noUnsafeMemberAccess from './no-unsafe-member-access';
import noUnsafeReturn from './no-unsafe-return';
import noUnusedExpressions from './no-unused-expressions';
Expand Down Expand Up @@ -207,6 +208,7 @@ export default {
'no-unsafe-argument': noUnsafeArgument,
'no-unsafe-assignment': noUnsafeAssignment,
'no-unsafe-call': noUnsafeCall,
'no-unsafe-declaration-merging': noUnsafeDeclarationMerging,
'no-unsafe-member-access': noUnsafeMemberAccess,
'no-unsafe-return': noUnsafeReturn,
'no-unused-expressions': noUnusedExpressions,
Expand Down
52 changes: 52 additions & 0 deletions packages/eslint-plugin/src/rules/no-unsafe-declaration-merging.ts
@@ -0,0 +1,52 @@
import type { TSESTree } from '@typescript-eslint/utils';
import * as ts from 'typescript';

import * as util from '../util';

export default util.createRule({
name: 'no-unsafe-declaration-merging',
meta: {
type: 'problem',
docs: {
description: 'Disallow unsafe declaration merging',
recommended: 'strict',
requiresTypeChecking: true,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should actually be able to do this without type info and just with the scope analysis APIs.

image
playground

You can see that if the names clash, then we can iterate through the variable.defs array and do a similar comparison as you've done here - variable.defs.some(def => def.node.type === unsafeType) where
unsafeType == AST_NODE_TYPES.TSInterfaceDeclaration | AST_NODE_TYPES.ClassDeclaration

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, I should finally get familiar with the scope manager 😄. #5854

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@yeonjuan do you have time to tackle this soon? I can if not, no worries 😄

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @bradzacher, @JoshuaKGoldberg I can fix this soon. I'll make a PR for it. (including fixing typo)
Thanks!

},
messages: {
unsafeMerging:
'Unsafe declaration merging between classes and interfaces.',
},
schema: [],
},
defaultOptions: [],
create(context) {
const parserServices = util.getParserServices(context);
const checker = parserServices.program.getTypeChecker();

function checkUnsafeDeclaration(
node: TSESTree.Identifier,
unsafeKind: ts.SyntaxKind,
): void {
const tsNode = parserServices.esTreeNodeToTSNodeMap.get(node);
const type = checker.getTypeAtLocation(tsNode);
const symbol = type.getSymbol();
if (symbol?.declarations?.some(decl => decl.kind === unsafeKind)) {
context.report({
node,
messageId: 'unsafeMerging',
});
}
}

return {
ClassDeclaration(node): void {
if (node.id) {
checkUnsafeDeclaration(node.id, ts.SyntaxKind.InterfaceDeclaration);
}
},
TSInterfaceDeclaration(node): void {
checkUnsafeDeclaration(node.id, ts.SyntaxKind.ClassDeclaration);
},
};
},
});
@@ -0,0 +1,124 @@
import rule from '../../src/rules/no-unsafe-declaration-merging';
import { getFixturesRootDir, RuleTester } from '../RuleTester';

const rootPath = getFixturesRootDir();

const ruleTester = new RuleTester({
parser: '@typescript-eslint/parser',
parserOptions: {
sourceType: 'module',
tsconfigRootDir: rootPath,
project: './tsconfig.json',
},
});

ruleTester.run('no-unsafe-declaration-merging', rule, {
valid: [
`
interface Foo {}
class Bar implements Foo {}
`,
`
namespace Foo {}
namespace Foo {}
`,
`
enum Foo {}
namespace Foo {}
`,
`
namespace Fooo {}
function Foo() {}
`,
`
const Foo = class {};
`,
`
interface Foo {
props: string;
}

function bar() {
return class Foo {};
}
`,
`
interface Foo {
props: string;
}

(function bar() {
class Foo {}
})();
`,
`
declare global {
interface Foo {}
}

class Foo {}
`,
],
invalid: [
{
code: `
interface Foo {}
class Foo {}
`,
errors: [
{
messageId: 'unsafeMerging',
JoshuaKGoldberg marked this conversation as resolved.
Show resolved Hide resolved
line: 2,
column: 11,
},
{
messageId: 'unsafeMerging',
line: 3,
column: 7,
},
],
},
{
code: `
namespace Foo {
export interface Bar {}
}
namespace Foo {
export class Bar {}
}
`,
errors: [
{
messageId: 'unsafeMerging',
line: 3,
column: 20,
},
{
messageId: 'unsafeMerging',
line: 6,
column: 16,
},
],
},
{
code: `
declare global {
interface Foo {}
class Foo {}
}
`,
errors: [
{
messageId: 'unsafeMerging',
line: 3,
column: 13,
},
{
messageId: 'unsafeMerging',
line: 4,
column: 9,
},
],
},
],
});
JoshuaKGoldberg marked this conversation as resolved.
Show resolved Hide resolved