Skip to content

Commit

Permalink
feat(eslint-plugin): add no-unnecessary-type-constraint rule
Browse files Browse the repository at this point in the history
  • Loading branch information
JoshuaKGoldberg committed Sep 8, 2020
1 parent ec7449d commit 23e14f2
Show file tree
Hide file tree
Showing 6 changed files with 415 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/eslint-plugin/README.md
Expand Up @@ -142,6 +142,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: | :thought_balloon: |
| [`@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 @@ -87,6 +87,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 @@ -64,6 +64,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 @@ -170,6 +171,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
116 changes: 116 additions & 0 deletions packages/eslint-plugin/src/rules/no-unnecessary-type-constraint.ts
@@ -0,0 +1,116 @@
import { 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'
>;

type KeywordFilter = (type: ts.Type) => boolean;

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,
requiresTypeChecking: true,
suggestion: true,
},
fixable: 'code',
messages: {
unnecessaryConstraint:
'Constraining a generic type to {{constraint}} does nothing and is unnecessary.',
},
schema: [],
type: 'suggestion',
},
defaultOptions: [],
create(context) {
const parserServices = util.getParserServices(context);
const checker = parserServices.program.getTypeChecker();

const keywordFilters: [KeywordFilter, string][] = [];
if (is3dot5) {
keywordFilters.push([util.isTypeUnknownType, 'unknown']);

if (is3dot9) {
keywordFilters.push([util.isTypeAnyType, 'any']);
}
}

if (!keywordFilters.length) {
return {};
}

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

const report = (
node: TypeParameterWithConstraint,
constraint: string,
inArrowFunction: boolean,
): void => {
context.report({
data: { constraint },
fix(fixer) {
return fixer.replaceTextRange(
[node.name.range[1], node.constraint.range[1]],
inArrowFunction && inJsx ? ',' : '',
);
},
messageId: 'unnecessaryConstraint',
node,
});
};

const checkNode = (
node: TypeParameterWithConstraint,
inArrowFunction: boolean,
): void => {
const constraint = parserServices.esTreeNodeToTSNodeMap.get(
node.constraint,
);
const constraintType = checker.getTypeAtLocation(constraint);

for (const [filter, type] of keywordFilters) {
if (filter(constraintType)) {
report(node, type, inArrowFunction);
return;
}
}
};

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 23e14f2

Please sign in to comment.