Skip to content

Commit

Permalink
feat(eslint-plugin): add rule no-unsafe-assignment
Browse files Browse the repository at this point in the history
  • Loading branch information
bradzacher committed Mar 7, 2020
1 parent e5db36f commit ef6a841
Show file tree
Hide file tree
Showing 9 changed files with 349 additions and 6 deletions.
1 change: 1 addition & 0 deletions packages/eslint-plugin/README.md
Expand Up @@ -132,6 +132,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-unsafe-assignment`](./docs/rules/no-unsafe-assignment.md) | Disallows assigning any to variables and properties | | | :thought_balloon: |
| [`@typescript-eslint/no-unsafe-call`](./docs/rules/no-unsafe-call.md) | Disallows calling an any type value | | | :thought_balloon: |
| [`@typescript-eslint/no-unsafe-member-access`](./docs/rules/no-unsafe-member-access.md) | Disallows member access on any typed variables | | | :thought_balloon: |
| [`@typescript-eslint/no-unsafe-return`](./docs/rules/no-unsafe-return.md) | Disallows returning any from a function | | | :thought_balloon: |
Expand Down
59 changes: 59 additions & 0 deletions packages/eslint-plugin/docs/rules/no-unsafe-assignment.md
@@ -0,0 +1,59 @@
# Disallows returning any from a function (`no-unsafe-return`)

Despite your best intentions, the `any` type can sometimes leak into your codebase.
Assigning an `any` typed value to a variable can be hard to pick up on, particularly if it leaks in from an external library. Operations on the variable will not checked at all by TypeScript, so it creates a potential safety hole, and source of bugs in your codebase.

## Rule Details

This rule disallows the assigning `any` to a variable, and assigning `any[]` to an array destructuring.
This rule also compares the assigned type to the variable's declared/inferred return type to ensure you don't return an unsafe `any` in a generic position to a receiver that's expecting a specific type. For example, it will error if you return `Set<any>` from a function declared as returning `Set<string>`.

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

```ts
const x = 1 as any,
y = 1 as any;
const [x] = 1 as any;
const [x] = [] as any[];

function foo(a = 1 as any) {}
class Foo {
constructor(private a = 1 as any) {}
}
class Foo {
private a = 1 as any;
}

// generic position examples
const x: Set<string> = new Set<any>();
const x: Map<string, string> = new Map<string, any>();
const x: Set<string[]> = new Set<any[]>();
const x: Set<Set<Set<string>>> = new Set<Set<Set<any>>>();
```

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

```ts
const x = 1,
y = 1;
const [x] = [1];

function foo(a = 1) {}
class Foo {
constructor(private a = 1) {}
}
class Foo {
private a = 1;
}

// generic position examples
const x: Set<string> = new Set<string>();
const x: Map<string, string> = new Map<string, string>();
const x: Set<string[]> = new Set<string[]>();
const x: Set<Set<Set<string>>> = new Set<Set<Set<string>>>();
```

## Related to

- [`no-explicit-any`](./no-explicit-any.md)
- TSLint: [`no-unsafe-any`](https://palantir.github.io/tslint/rules/no-unsafe-any/)
2 changes: 1 addition & 1 deletion packages/eslint-plugin/docs/rules/no-unsafe-call.md
@@ -1,7 +1,7 @@
# Disallows calling an any type value (`no-unsafe-call`)

Despite your best intentions, the `any` type can sometimes leak into your codebase.
Member access on `any` typed variables is not checked at all by TypeScript, so it creates a potential safety hole, and source of bugs in your codebase.
The arguments to, and return value of calling an `any` typed variable are not checked at all by TypeScript, so it creates a potential safety hole, and source of bugs in your codebase.

## Rule Details

Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/configs/all.json
Expand Up @@ -61,6 +61,7 @@
"@typescript-eslint/no-unnecessary-qualifier": "error",
"@typescript-eslint/no-unnecessary-type-arguments": "error",
"@typescript-eslint/no-unnecessary-type-assertion": "error",
"@typescript-eslint/no-unsafe-assignment": "error",
"@typescript-eslint/no-unsafe-call": "error",
"@typescript-eslint/no-unsafe-member-access": "error",
"@typescript-eslint/no-unsafe-return": "error",
Expand Down
2 changes: 2 additions & 0 deletions packages/eslint-plugin/src/rules/index.ts
Expand Up @@ -53,6 +53,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 noUnsafeAssignment from './no-unsafe-assignment';
import noUnsafeCall from './no-unsafe-call';
import noUnsafeMemberAccess from './no-unsafe-member-access';
import noUnsafeReturn from './no-unsafe-return';
Expand Down Expand Up @@ -147,6 +148,7 @@ export default {
'no-unnecessary-qualifier': noUnnecessaryQualifier,
'no-unnecessary-type-arguments': noUnnecessaryTypeArguments,
'no-unnecessary-type-assertion': noUnnecessaryTypeAssertion,
'no-unsafe-assignment': noUnsafeAssignment,
'no-unsafe-call': noUnsafeCall,
'no-unsafe-member-access': noUnsafeMemberAccess,
'no-unsafe-return': noUnsafeReturn,
Expand Down
133 changes: 133 additions & 0 deletions packages/eslint-plugin/src/rules/no-unsafe-assignment.ts
@@ -0,0 +1,133 @@
import {
TSESTree,
AST_NODE_TYPES,
} from '@typescript-eslint/experimental-utils';
import * as util from '../util';

const enum ComparisonType {
/** Do no assignment comparison */
None,
/** Use the receiver's type for comparison */
Basic,
/** Use the sender's contextual type for comparison */
Contextual,
}

export default util.createRule({
name: 'no-unsafe-assignment',
meta: {
type: 'problem',
docs: {
description: 'Disallows assigning any to variables and properties',
category: 'Possible Errors',
recommended: false,
requiresTypeChecking: true,
},
messages: {
anyAssignment: 'Unsafe assignment of an any value',
unsafeArrayPattern: 'Unsafe array destructuring of an any array value',
unsafeAssignment:
'Unsafe asignment of type {{sender}} to a variable of type {{receiver}}',
},
schema: [],
},
defaultOptions: [],
create(context) {
const { program, esTreeNodeToTSNodeMap } = util.getParserServices(context);
const checker = program.getTypeChecker();

function checkAssignment(
receiverNode: TSESTree.Node,
senderNode: TSESTree.Node,
reportingNode: TSESTree.Node,
comparisonType: ComparisonType,
): void {
const receiverType = checker.getTypeAtLocation(
esTreeNodeToTSNodeMap.get(receiverNode),
);
const senderType = checker.getTypeAtLocation(
esTreeNodeToTSNodeMap.get(senderNode),
);

if (util.isTypeAnyType(senderType)) {
return context.report({
node: reportingNode,
messageId: 'anyAssignment',
});
}

if (
receiverNode.type === AST_NODE_TYPES.ArrayPattern &&
util.isTypeAnyArrayType(senderType, checker)
) {
return context.report({
node: reportingNode,
messageId: 'unsafeArrayPattern',
});
}

if (comparisonType === ComparisonType.None) {
return;
}

const result = util.isUnsafeAssignment(senderType, receiverType, checker);
if (!result) {
return;
}

const { sender, receiver } = result;
return context.report({
node: reportingNode,
messageId: 'unsafeAssignment',
data: {
sender: checker.typeToString(sender),
receiver: checker.typeToString(receiver),
},
});
}

function getComparisonType(
typeAnnotation: TSESTree.TSTypeAnnotation | undefined,
): ComparisonType {
return typeAnnotation
? // if there's a type annotation, we can do a comparison
ComparisonType.Basic
: // no type annotation means the variable's type will just be inferred, thus equal
ComparisonType.None;
}

return {
'VariableDeclarator[init != null]'(
node: TSESTree.VariableDeclarator,
): void {
checkAssignment(
node.id,
node.init!,
node,
getComparisonType(node.id.typeAnnotation),
);
},
'ClassProperty[value != null]'(node: TSESTree.ClassProperty): void {
checkAssignment(
node.key,
node.value!,
node,
getComparisonType(node.typeAnnotation),
);
},
'AssignmentExpression[operator = "="], AssignmentPattern'(
node: TSESTree.AssignmentExpression | TSESTree.AssignmentPattern,
): void {
checkAssignment(
node.left,
node.right,
node,
// the variable already has some form of a type to compare against
ComparisonType.Basic,
);
},

// TODO - { x: 1 }
};
},
});
18 changes: 14 additions & 4 deletions packages/eslint-plugin/src/util/types.ts
Expand Up @@ -304,6 +304,19 @@ export function isTypeAnyType(type: ts.Type): boolean {
return isTypeFlagSet(type, ts.TypeFlags.Any);
}

/**
* @returns true if the type is `any[]`
*/
export function isTypeAnyArrayType(
type: ts.Type,
checker: ts.TypeChecker,
): boolean {
return (
checker.isArrayType(type) &&
isTypeAnyType(checker.getTypeArguments(type)[0])
);
}

export const enum AnyType {
Any,
AnyArray,
Expand All @@ -321,10 +334,7 @@ export function isAnyOrAnyArrayTypeDiscriminated(
if (isTypeAnyType(type)) {
return AnyType.Any;
}
if (
checker.isArrayType(type) &&
isTypeAnyType(checker.getTypeArguments(type)[0])
) {
if (isTypeAnyArrayType(type, checker)) {
return AnyType.AnyArray;
}
return AnyType.Safe;
Expand Down

0 comments on commit ef6a841

Please sign in to comment.