Skip to content

Commit

Permalink
feat(eslint-plugin): add no-unnecessary-type-constraint rule (#2516)
Browse files Browse the repository at this point in the history
* feat(eslint-plugin): add no-unnecessary-type-constraint rule

* Inlined report

* Improved message and removed type checker

* Stop testing with type info
  • Loading branch information
Josh Goldberg committed Oct 26, 2020
1 parent ef8b5a7 commit 880ac75
Show file tree
Hide file tree
Showing 6 changed files with 392 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/eslint-plugin/README.md
Expand Up @@ -143,6 +143,7 @@ Pro Tip: For larger codebases you may want to consider splitting our linting int
| [`@typescript-eslint/no-unnecessary-qualifier`](./docs/rules/no-unnecessary-qualifier.md) | Warns when a namespace qualifier is unnecessary | | :wrench: | :thought_balloon: |
| [`@typescript-eslint/no-unnecessary-type-arguments`](./docs/rules/no-unnecessary-type-arguments.md) | Enforces that type arguments will not be used if not required | | :wrench: | :thought_balloon: |
| [`@typescript-eslint/no-unnecessary-type-assertion`](./docs/rules/no-unnecessary-type-assertion.md) | Warns if a type assertion does not change the type of an expression | :heavy_check_mark: | :wrench: | :thought_balloon: |
| [`@typescript-eslint/no-unnecessary-type-constraint`](./docs/rules/no-unnecessary-type-constraint.md) | Disallows unnecessary constraints on generic types | | :wrench: | |
| [`@typescript-eslint/no-unsafe-assignment`](./docs/rules/no-unsafe-assignment.md) | Disallows assigning any to variables and properties | :heavy_check_mark: | | :thought_balloon: |
| [`@typescript-eslint/no-unsafe-call`](./docs/rules/no-unsafe-call.md) | Disallows calling an any type value | :heavy_check_mark: | | :thought_balloon: |
| [`@typescript-eslint/no-unsafe-member-access`](./docs/rules/no-unsafe-member-access.md) | Disallows member access on any typed variables | :heavy_check_mark: | | :thought_balloon: |
Expand Down
@@ -0,0 +1,55 @@
# Disallows unnecessary constraints on generic types (`no-unnecessary-type-constraint`)

## Rule Details

Type parameters (`<T>`) may be "constrained" with an `extends` keyword ([docs](https://www.typescriptlang.org/docs/handbook/generics.html#generic-constraints)).
When not provided, type parameters happen to default to:

- As of TypeScript 3.9: `unknown` ([docs](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-9.html#type-parameters-that-extend-any-no-longer-act-as-any))
- Before that, as of 3.5: `any` ([docs](https://devblogs.microsoft.com/typescript/announcing-typescript-3-5/#breaking-changes))

It is therefore redundant to `extend` from these types in later versions of TypeScript.

Examples of **incorrect** code for this rule:

```ts
interface FooAny<T extends any> {}
interface FooUnknown<T extends unknown> {}

type BarAny<T extends any> = {};
type BarUnknown<T extends unknown> = {};

class BazAny<T extends any> {
quxUnknown<U extends unknown>() {}
}

class BazUnknown<T extends unknown> {
quxUnknown<U extends unknown>() {}
}

const QuuxAny = <T extends any>() => {};
const QuuxUnknown = <T extends unknown>() => {};

function QuuzAny<T extends any>() {}
function QuuzUnknown<T extends unknown>() {}
```

Examples of **correct** code for this rule:

```ts
interface Foo<T> {}

type Bar<T> = {};

class Baz<T> {
qux<U> { }
}

const Quux = <T>() => {};

function Quuz<T>() {}
```

## When Not To Use It

If you don't care about the specific styles of your type constraints, or never use them in the first place, then you will not need this rule.
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/configs/all.ts
Expand Up @@ -92,6 +92,7 @@ export = {
'@typescript-eslint/no-type-alias': 'error',
'@typescript-eslint/no-unnecessary-boolean-literal-compare': 'error',
'@typescript-eslint/no-unnecessary-condition': 'error',
'@typescript-eslint/no-unnecessary-type-constraint': 'error',
'@typescript-eslint/no-unnecessary-qualifier': 'error',
'@typescript-eslint/no-unnecessary-type-arguments': 'error',
'@typescript-eslint/no-unnecessary-type-assertion': 'error',
Expand Down
2 changes: 2 additions & 0 deletions packages/eslint-plugin/src/rules/index.ts
Expand Up @@ -67,6 +67,7 @@ import noUnnecessaryCondition from './no-unnecessary-condition';
import noUnnecessaryQualifier from './no-unnecessary-qualifier';
import noUnnecessaryTypeArguments from './no-unnecessary-type-arguments';
import noUnnecessaryTypeAssertion from './no-unnecessary-type-assertion';
import noUnnecessaryTypeConstraint from './no-unnecessary-type-constraint';
import noUnsafeAssignment from './no-unsafe-assignment';
import noUnsafeCall from './no-unsafe-call';
import noUnsafeMemberAccess from './no-unsafe-member-access';
Expand Down Expand Up @@ -177,6 +178,7 @@ export default {
'no-unnecessary-qualifier': noUnnecessaryQualifier,
'no-unnecessary-type-arguments': noUnnecessaryTypeArguments,
'no-unnecessary-type-assertion': noUnnecessaryTypeAssertion,
'no-unnecessary-type-constraint': noUnnecessaryTypeConstraint,
'no-unsafe-assignment': noUnsafeAssignment,
'no-unsafe-call': noUnsafeCall,
'no-unsafe-member-access': noUnsafeMemberAccess,
Expand Down
103 changes: 103 additions & 0 deletions packages/eslint-plugin/src/rules/no-unnecessary-type-constraint.ts
@@ -0,0 +1,103 @@
import {
AST_NODE_TYPES,
TSESTree,
} from '@typescript-eslint/experimental-utils';
import * as semver from 'semver';
import * as ts from 'typescript';
import * as util from '../util';

type MakeRequired<Base, Key extends keyof Base> = Omit<Base, Key> &
Required<Pick<Base, Key>>;

type TypeParameterWithConstraint = MakeRequired<
TSESTree.TSTypeParameter,
'constraint'
>;

const is3dot5 = semver.satisfies(
ts.version,
`>= 3.5.0 || >= 3.5.1-rc || >= 3.5.0-beta`,
{
includePrerelease: true,
},
);

const is3dot9 =
is3dot5 &&
semver.satisfies(ts.version, `>= 3.9.0 || >= 3.9.1-rc || >= 3.9.0-beta`, {
includePrerelease: true,
});

export default util.createRule({
name: 'no-unnecessary-type-constraint',
meta: {
docs: {
category: 'Best Practices',
description: 'Disallows unnecessary constraints on generic types',
recommended: false,
suggestion: true,
},
fixable: 'code',
messages: {
unnecessaryConstraint:
'Constraining the generic type `{{name}}` to `{{constraint}}` does nothing and is unnecessary.',
},
schema: [],
type: 'suggestion',
},
defaultOptions: [],
create(context) {
if (!is3dot5) {
return {};
}

// In theory, we could use the type checker for more advanced constraint types...
// ...but in practice, these types are rare, and likely not worth requiring type info.
// https://github.com/typescript-eslint/typescript-eslint/pull/2516#discussion_r495731858
const unnecessaryConstraints = is3dot9
? new Map([
[AST_NODE_TYPES.TSAnyKeyword, 'any'],
[AST_NODE_TYPES.TSUnknownKeyword, 'unknown'],
])
: new Map([[AST_NODE_TYPES.TSUnknownKeyword, 'unknown']]);

const inJsx = context.getFilename().toLowerCase().endsWith('tsx');

const checkNode = (
node: TypeParameterWithConstraint,
inArrowFunction: boolean,
): void => {
const constraint = unnecessaryConstraints.get(node.constraint.type);

if (constraint) {
context.report({
data: {
constraint,
name: node.name.name,
},
fix(fixer) {
return fixer.replaceTextRange(
[node.name.range[1], node.constraint.range[1]],
inArrowFunction && inJsx ? ',' : '',
);
},
messageId: 'unnecessaryConstraint',
node,
});
}
};

return {
':not(ArrowFunctionExpression) > TSTypeParameterDeclaration > TSTypeParameter[constraint]'(
node: TypeParameterWithConstraint,
): void {
checkNode(node, false);
},
'ArrowFunctionExpression > TSTypeParameterDeclaration > TSTypeParameter[constraint]'(
node: TypeParameterWithConstraint,
): void {
checkNode(node, true);
},
};
},
});

0 comments on commit 880ac75

Please sign in to comment.