From a49b860cbbb2c7d718b99f561e2fb6eaadf16f17 Mon Sep 17 00:00:00 2001 From: Brad Zacher Date: Thu, 9 Apr 2020 09:45:06 -0700 Subject: [PATCH] feat(eslint-plugin): add rule no-unsafe-assignment (#1694) --- packages/eslint-plugin/README.md | 1 + .../docs/rules/no-unsafe-assignment.md | 62 +++ .../docs/rules/no-unsafe-call.md | 2 +- packages/eslint-plugin/src/configs/all.json | 1 + packages/eslint-plugin/src/rules/index.ts | 2 + .../src/rules/no-unsafe-assignment.ts | 370 ++++++++++++++++++ packages/eslint-plugin/src/util/types.ts | 49 ++- .../tests/rules/no-unsafe-assignment.test.ts | 327 ++++++++++++++++ .../src/ts-estree/ts-estree.ts | 2 +- 9 files changed, 802 insertions(+), 14 deletions(-) create mode 100644 packages/eslint-plugin/docs/rules/no-unsafe-assignment.md create mode 100644 packages/eslint-plugin/src/rules/no-unsafe-assignment.ts create mode 100644 packages/eslint-plugin/tests/rules/no-unsafe-assignment.test.ts diff --git a/packages/eslint-plugin/README.md b/packages/eslint-plugin/README.md index 92131acf458..809aac848a6 100644 --- a/packages/eslint-plugin/README.md +++ b/packages/eslint-plugin/README.md @@ -134,6 +134,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: | diff --git a/packages/eslint-plugin/docs/rules/no-unsafe-assignment.md b/packages/eslint-plugin/docs/rules/no-unsafe-assignment.md new file mode 100644 index 00000000000..5cb6e8d61c2 --- /dev/null +++ b/packages/eslint-plugin/docs/rules/no-unsafe-assignment.md @@ -0,0 +1,62 @@ +# Disallows assigning any to variables and properties (`no-unsafe-assignment`) + +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` from a function declared as returning `Set`. + +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[]; +const [x] = [1 as any]; +[x] = [1] 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 = new Set(); +const x: Map = new Map(); +const x: Set = new Set(); +const x: Set>> = new Set>>(); +``` + +Examples of **correct** code for this rule: + +```ts +const x = 1, + y = 1; +const [x] = [1]; +[x] = [1] as [number]; + +function foo(a = 1) {} +class Foo { + constructor(private a = 1) {} +} +class Foo { + private a = 1; +} + +// generic position examples +const x: Set = new Set(); +const x: Map = new Map(); +const x: Set = new Set(); +const x: Set>> = new Set>>(); +``` + +## Related to + +- [`no-explicit-any`](./no-explicit-any.md) +- TSLint: [`no-unsafe-any`](https://palantir.github.io/tslint/rules/no-unsafe-any/) diff --git a/packages/eslint-plugin/docs/rules/no-unsafe-call.md b/packages/eslint-plugin/docs/rules/no-unsafe-call.md index 3c18b7c1ee2..490ff78ced5 100644 --- a/packages/eslint-plugin/docs/rules/no-unsafe-call.md +++ b/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 diff --git a/packages/eslint-plugin/src/configs/all.json b/packages/eslint-plugin/src/configs/all.json index cfcb38ced24..85cf2e1ecc6 100644 --- a/packages/eslint-plugin/src/configs/all.json +++ b/packages/eslint-plugin/src/configs/all.json @@ -63,6 +63,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", diff --git a/packages/eslint-plugin/src/rules/index.ts b/packages/eslint-plugin/src/rules/index.ts index 332c706c832..15ce8dd1a82 100644 --- a/packages/eslint-plugin/src/rules/index.ts +++ b/packages/eslint-plugin/src/rules/index.ts @@ -55,6 +55,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'; @@ -151,6 +152,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, diff --git a/packages/eslint-plugin/src/rules/no-unsafe-assignment.ts b/packages/eslint-plugin/src/rules/no-unsafe-assignment.ts new file mode 100644 index 00000000000..60f7b78acc0 --- /dev/null +++ b/packages/eslint-plugin/src/rules/no-unsafe-assignment.ts @@ -0,0 +1,370 @@ +import { + TSESTree, + AST_NODE_TYPES, +} from '@typescript-eslint/experimental-utils'; +import * as ts from 'typescript'; +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', + unsafeArrayPatternFromTuple: + 'Unsafe array destructuring of a tuple element with an any value', + unsafeAssignment: + 'Unsafe asignment of type {{sender}} to a variable of type {{receiver}}', + unsafeArraySpread: 'Unsafe spread of an any value in an array', + }, + schema: [], + }, + defaultOptions: [], + create(context) { + const { program, esTreeNodeToTSNodeMap } = util.getParserServices(context); + const checker = program.getTypeChecker(); + + // returns true if the assignment reported + function checkArrayDestructureHelper( + receiverNode: TSESTree.Node, + senderNode: TSESTree.Node, + ): boolean { + if (receiverNode.type !== AST_NODE_TYPES.ArrayPattern) { + return false; + } + + const senderTsNode = esTreeNodeToTSNodeMap.get(senderNode); + const senderType = checker.getTypeAtLocation(senderTsNode); + + return checkArrayDestructure(receiverNode, senderType, senderTsNode); + } + + // returns true if the assignment reported + function checkArrayDestructure( + receiverNode: TSESTree.ArrayPattern, + senderType: ts.Type, + senderNode: ts.Node, + ): boolean { + // any array + // const [x] = ([] as any[]); + if (util.isTypeAnyArrayType(senderType, checker)) { + context.report({ + node: receiverNode, + messageId: 'unsafeArrayPattern', + }); + return false; + } + + if (!checker.isTupleType(senderType)) { + return true; + } + + const tupleElements = util.getTypeArguments(senderType, checker); + + // tuple with any + // const [x] = [1 as any]; + let didReport = false; + for ( + let receiverIndex = 0; + receiverIndex < receiverNode.elements.length; + receiverIndex += 1 + ) { + const receiverElement = receiverNode.elements[receiverIndex]; + if (!receiverElement) { + continue; + } + + if (receiverElement.type === AST_NODE_TYPES.RestElement) { + // don't handle rests as they're not a 1:1 assignment + continue; + } + + const senderType = tupleElements[receiverIndex] as ts.Type | undefined; + if (!senderType) { + continue; + } + + // check for the any type first so we can handle [[[x]]] = [any] + if (util.isTypeAnyType(senderType)) { + context.report({ + node: receiverElement, + messageId: 'unsafeArrayPatternFromTuple', + }); + // we want to report on every invalid element in the tuple + didReport = true; + } else if (receiverElement.type === AST_NODE_TYPES.ArrayPattern) { + didReport = checkArrayDestructure( + receiverElement, + senderType, + senderNode, + ); + } else if (receiverElement.type === AST_NODE_TYPES.ObjectPattern) { + didReport = checkObjectDestructure( + receiverElement, + senderType, + senderNode, + ); + } + } + + return didReport; + } + + // returns true if the assignment reported + function checkObjectDestructureHelper( + receiverNode: TSESTree.Node, + senderNode: TSESTree.Node, + ): boolean { + if (receiverNode.type !== AST_NODE_TYPES.ObjectPattern) { + return false; + } + + const senderTsNode = esTreeNodeToTSNodeMap.get(senderNode); + const senderType = checker.getTypeAtLocation(senderTsNode); + + return checkObjectDestructure(receiverNode, senderType, senderTsNode); + } + + // returns true if the assignment reported + function checkObjectDestructure( + receiverNode: TSESTree.ObjectPattern, + senderType: ts.Type, + senderNode: ts.Node, + ): boolean { + const properties = new Map( + senderType + .getProperties() + .map(property => [ + property.getName(), + checker.getTypeOfSymbolAtLocation(property, senderNode), + ]), + ); + + let didReport = false; + for ( + let receiverIndex = 0; + receiverIndex < receiverNode.properties.length; + receiverIndex += 1 + ) { + const receiverProperty = receiverNode.properties[receiverIndex]; + if (receiverProperty.type === AST_NODE_TYPES.RestElement) { + // don't bother checking rest + continue; + } + + let key: string; + if (receiverProperty.computed === false) { + key = + receiverProperty.key.type === AST_NODE_TYPES.Identifier + ? receiverProperty.key.name + : String(receiverProperty.key.value); + } else if (receiverProperty.key.type === AST_NODE_TYPES.Literal) { + key = String(receiverProperty.key.value); + } else if ( + receiverProperty.key.type === AST_NODE_TYPES.TemplateLiteral && + receiverProperty.key.quasis.length === 1 + ) { + key = String(receiverProperty.key.quasis[0].value.cooked); + } else { + // can't figure out the name, so skip it + continue; + } + + const senderType = properties.get(key); + if (!senderType) { + continue; + } + + // check for the any type first so we can handle {x: {y: z}} = {x: any} + if (util.isTypeAnyType(senderType)) { + context.report({ + node: receiverProperty.value, + messageId: 'unsafeArrayPatternFromTuple', + }); + didReport = true; + } else if ( + receiverProperty.value.type === AST_NODE_TYPES.ArrayPattern + ) { + didReport = checkArrayDestructure( + receiverProperty.value, + senderType, + senderNode, + ); + } else if ( + receiverProperty.value.type === AST_NODE_TYPES.ObjectPattern + ) { + didReport = checkObjectDestructure( + receiverProperty.value, + senderType, + senderNode, + ); + } + } + + return didReport; + } + + // returns true if the assignment reported + function checkAssignment( + receiverNode: TSESTree.Node, + senderNode: TSESTree.Expression, + reportingNode: TSESTree.Node, + comparisonType: ComparisonType, + ): boolean { + const receiverTsNode = esTreeNodeToTSNodeMap.get(receiverNode); + const receiverType = + comparisonType === ComparisonType.Contextual + ? util.getContextualType(checker, receiverTsNode as ts.Expression) ?? + checker.getTypeAtLocation(receiverTsNode) + : checker.getTypeAtLocation(receiverTsNode); + const senderType = checker.getTypeAtLocation( + esTreeNodeToTSNodeMap.get(senderNode), + ); + + if (util.isTypeAnyType(senderType)) { + context.report({ + node: reportingNode, + messageId: 'anyAssignment', + }); + return true; + } + + if (comparisonType === ComparisonType.None) { + return false; + } + + const result = util.isUnsafeAssignment(senderType, receiverType, checker); + if (!result) { + return false; + } + + const { sender, receiver } = result; + context.report({ + node: reportingNode, + messageId: 'unsafeAssignment', + data: { + sender: checker.typeToString(sender), + receiver: checker.typeToString(receiver), + }, + }); + return true; + } + + 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 { + const init = util.nullThrows( + node.init, + util.NullThrowsReasons.MissingToken(node.type, 'init'), + ); + let didReport = checkAssignment( + node.id, + init, + node, + getComparisonType(node.id.typeAnnotation), + ); + + if (!didReport) { + didReport = checkArrayDestructureHelper(node.id, init); + } + if (!didReport) { + checkObjectDestructureHelper(node.id, init); + } + }, + '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 { + let didReport = checkAssignment( + node.left, + node.right, + node, + // the variable already has some form of a type to compare against + ComparisonType.Basic, + ); + + if (!didReport) { + didReport = checkArrayDestructureHelper(node.left, node.right); + } + if (!didReport) { + checkObjectDestructureHelper(node.left, node.right); + } + }, + // object pattern props are checked via assignments + ':not(ObjectPattern) > Property'(node: TSESTree.Property): void { + if (node.value.type === AST_NODE_TYPES.AssignmentPattern) { + // handled by other selector + return; + } + + checkAssignment(node.key, node.value, node, ComparisonType.Contextual); + }, + 'ArrayExpression > SpreadElement'(node: TSESTree.SpreadElement): void { + const resetNode = esTreeNodeToTSNodeMap.get(node.argument); + const restType = checker.getTypeAtLocation(resetNode); + if ( + util.isTypeAnyType(restType) || + util.isTypeAnyArrayType(restType, checker) + ) { + context.report({ + node: node, + messageId: 'unsafeArraySpread', + }); + } + }, + 'JSXAttribute[value != null]'(node: TSESTree.JSXAttribute): void { + const value = util.nullThrows( + node.value, + util.NullThrowsReasons.MissingToken(node.type, 'value'), + ); + if ( + value.type !== AST_NODE_TYPES.JSXExpressionContainer || + value.expression.type === AST_NODE_TYPES.JSXEmptyExpression + ) { + return; + } + + checkAssignment( + node.name, + value.expression, + value.expression, + ComparisonType.Contextual, + ); + }, + }; + }, +}); diff --git a/packages/eslint-plugin/src/util/types.ts b/packages/eslint-plugin/src/util/types.ts index f602a1e6a27..ae6ee3843aa 100644 --- a/packages/eslint-plugin/src/util/types.ts +++ b/packages/eslint-plugin/src/util/types.ts @@ -1,6 +1,7 @@ import { isCallExpression, isJsxExpression, + isIdentifier, isNewExpression, isParameterDeclaration, isPropertyDeclaration, @@ -8,6 +9,7 @@ import { isUnionOrIntersectionType, isVariableDeclaration, unionTypeParts, + isPropertyAssignment, } from 'tsutils'; import * as ts from 'typescript'; @@ -297,6 +299,18 @@ export function getEqualsKind(operator: string): EqualsKind | undefined { } } +export function getTypeArguments( + type: ts.TypeReference, + checker: ts.TypeChecker, +): readonly ts.Type[] { + // getTypeArguments was only added in TS3.7 + if (checker.getTypeArguments) { + return checker.getTypeArguments(type); + } + + return type.typeArguments ?? []; +} + /** * @returns true if the type is `any` */ @@ -304,6 +318,22 @@ 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( + // getTypeArguments was only added in TS3.7 + getTypeArguments(type, checker)[0], + ) + ); +} + export const enum AnyType { Any, AnyArray, @@ -321,15 +351,7 @@ export function isAnyOrAnyArrayTypeDiscriminated( if (isTypeAnyType(type)) { return AnyType.Any; } - if ( - checker.isArrayType(type) && - isTypeAnyType( - // getTypeArguments was only added in TS3.7 - checker.getTypeArguments - ? checker.getTypeArguments(type)[0] - : (type.typeArguments ?? [])[0], - ) - ) { + if (isTypeAnyArrayType(type, checker)) { return AnyType.AnyArray; } return AnyType.Safe; @@ -350,6 +372,10 @@ export function isUnsafeAssignment( receiver: ts.Type, checker: ts.TypeChecker, ): false | { sender: ts.Type; receiver: ts.Type } { + if (isTypeAnyType(type) && !isTypeAnyType(receiver)) { + return { sender: type, receiver }; + } + if (isTypeReference(type) && isTypeReference(receiver)) { // TODO - figure out how to handle cases like this, // where the types are assignable, but not the same type @@ -386,9 +412,6 @@ export function isUnsafeAssignment( return false; } - if (isTypeAnyType(type) && !isTypeAnyType(receiver)) { - return { sender: type, receiver }; - } return false; } @@ -419,6 +442,8 @@ export function getContextualType( return parent.type ? checker.getTypeFromTypeNode(parent.type) : undefined; } else if (isJsxExpression(parent)) { return checker.getContextualType(parent); + } else if (isPropertyAssignment(parent) && isIdentifier(node)) { + return checker.getContextualType(node); } else if ( ![ts.SyntaxKind.TemplateSpan, ts.SyntaxKind.JsxExpression].includes( parent.kind, diff --git a/packages/eslint-plugin/tests/rules/no-unsafe-assignment.test.ts b/packages/eslint-plugin/tests/rules/no-unsafe-assignment.test.ts new file mode 100644 index 00000000000..708969310ed --- /dev/null +++ b/packages/eslint-plugin/tests/rules/no-unsafe-assignment.test.ts @@ -0,0 +1,327 @@ +import { TSESLint } from '@typescript-eslint/experimental-utils'; +import rule from '../../src/rules/no-unsafe-assignment'; +import { + RuleTester, + batchedSingleLineTests, + getFixturesRootDir, + noFormat, +} from '../RuleTester'; +import { + InferMessageIdsTypeFromRule, + InferOptionsTypeFromRule, +} from '../../src/util'; + +type Options = InferOptionsTypeFromRule; +type MessageIds = InferMessageIdsTypeFromRule; +type InvalidTest = TSESLint.InvalidTestCase; + +function assignmentTest( + tests: [string, number, number, boolean?][], +): InvalidTest[] { + return tests.reduce( + (acc, [assignment, column, endColumn, skipAssignmentExpression]) => { + // VariableDeclaration + acc.push({ + code: `const ${assignment}`, + errors: [ + { + messageId: 'unsafeArrayPatternFromTuple', + line: 1, + column: column + 6, + endColumn: endColumn + 6, + }, + ], + }); + // AssignmentPattern + acc.push({ + code: `function foo(${assignment}) {}`, + errors: [ + { + messageId: 'unsafeArrayPatternFromTuple', + line: 1, + column: column + 13, + endColumn: endColumn + 13, + }, + ], + }); + // AssignmentExpression + if (skipAssignmentExpression !== true) { + acc.push({ + code: `(${assignment})`, + errors: [ + { + messageId: 'unsafeArrayPatternFromTuple', + line: 1, + column: column + 1, + endColumn: endColumn + 1, + }, + ], + }); + } + + return acc; + }, + [], + ); +} + +const ruleTester = new RuleTester({ + parser: '@typescript-eslint/parser', + parserOptions: { + project: './tsconfig.json', + tsconfigRootDir: getFixturesRootDir(), + }, +}); + +ruleTester.run('no-unsafe-assignment', rule, { + valid: [ + 'const x = 1;', + 'const x: number = 1;', + ` +const x = 1, + y = 1; + `, + 'let x;', + ` +let x = 1, + y; + `, + 'function foo(a = 1) {}', + ` +class Foo { + constructor(private a = 1) {} +} + `, + ` +class Foo { + private a = 1; +} + `, + 'const x: Set = new Set();', + 'const x: Set = new Set();', + 'const [x] = [1];', + 'const [x, ...y] = [1, 2, 3, 4, 5];', + 'const [x, ...y] = [1];', + 'function foo(x = 1) {}', + 'function foo([x] = [1]) {}', + 'function foo([x, ...y] = [1, 2, 3, 4, 5]) {}', + 'function foo([x, ...y] = [1]) {}', + // this is not checked, because there's no annotation to compare it with + 'const x = new Set();', + 'const x = { y: 1 };', + 'const x: { y: number } = { y: 1 };', + 'const x = [...[1, 2, 3]];', + { + code: ` +type Props = { a: string }; +declare function Foo(props: Props): never; +; + `, + filename: 'react.tsx', + }, + ], + invalid: [ + ...batchedSingleLineTests({ + code: noFormat` +const x = (1 as any); +const x = (1 as any), y = 1; +function foo(a = (1 as any)) {} +class Foo { constructor(private a = (1 as any)) {} } +class Foo { private a = (1 as any) } + `, + errors: [ + { + messageId: 'anyAssignment', + line: 2, + column: 7, + endColumn: 21, + }, + { + messageId: 'anyAssignment', + line: 3, + column: 7, + endColumn: 21, + }, + { + messageId: 'anyAssignment', + line: 4, + column: 14, + endColumn: 28, + }, + { + messageId: 'anyAssignment', + line: 5, + column: 33, + endColumn: 47, + }, + { + messageId: 'anyAssignment', + line: 6, + column: 13, + endColumn: 35, + }, + ], + }), + ...batchedSingleLineTests({ + code: ` +const [x] = 1 as any; +const [x] = [] as any[]; + `, + errors: [ + { + messageId: 'anyAssignment', + line: 2, + column: 7, + endColumn: 21, + }, + { + messageId: 'unsafeArrayPattern', + line: 3, + column: 7, + endColumn: 10, + }, + ], + }), + ...batchedSingleLineTests({ + code: noFormat` +const x: Set = new Set(); +const x: Map = new Map(); +const x: Set = new Set(); +const x: Set>> = new Set>>(); + `, + errors: [ + { + messageId: 'unsafeAssignment', + data: { + sender: 'Set', + receiver: 'Set', + }, + line: 2, + }, + { + messageId: 'unsafeAssignment', + data: { + sender: 'Map', + receiver: 'Map', + }, + line: 3, + }, + { + messageId: 'unsafeAssignment', + data: { + sender: 'Set', + receiver: 'Set', + }, + line: 4, + }, + { + messageId: 'unsafeAssignment', + data: { + sender: 'Set>>', + receiver: 'Set>>', + }, + line: 5, + }, + ], + }), + ...assignmentTest([ + ['[x] = [1] as [any]', 2, 3], + ['[[[[x]]]] = [[[[1 as any]]]]', 5, 6], + ['[[[[x]]]] = [1 as any]', 2, 9, true], + ['[{x}] = [{x: 1}] as [{x: any}]', 3, 4], + ]), + { + // TS treats the assignment pattern weirdly in this case + code: '[[[[x]]]] = [1 as any];', + errors: [ + { + messageId: 'unsafeAssignment', + line: 1, + column: 1, + endColumn: 23, + }, + ], + }, + ...batchedSingleLineTests({ + code: ` +const x = [...(1 as any)]; +const x = [...([] as any[])]; + `, + errors: [ + { + messageId: 'unsafeArraySpread', + line: 2, + column: 12, + endColumn: 25, + }, + { + messageId: 'unsafeArraySpread', + line: 3, + column: 12, + endColumn: 28, + }, + ], + }), + ...assignmentTest([ + ['{x} = {x: 1} as {x: any}', 2, 3], + ['{x: y} = {x: 1} as {x: any}', 5, 6], + ['{x: {y}} = {x: {y: 1}} as {x: {y: any}}', 6, 7], + ['{x: [y]} = {x: {y: 1}} as {x: [any]}', 6, 7], + ]), + ...batchedSingleLineTests({ + code: ` +const x = { y: 1 as any }; +const x = { y: { z: 1 as any } }; +const x: { y: Set>> } = { y: new Set>>() }; +const x = { ...(1 as any) }; + `, + errors: [ + { + messageId: 'anyAssignment', + line: 2, + column: 13, + endColumn: 24, + }, + { + messageId: 'anyAssignment', + line: 3, + column: 18, + endColumn: 29, + }, + { + messageId: 'unsafeAssignment', + line: 4, + column: 43, + endColumn: 70, + data: { + sender: 'Set>>', + receiver: 'Set>>', + }, + }, + { + // spreading an any widens the object type to any + messageId: 'anyAssignment', + line: 5, + column: 7, + endColumn: 28, + }, + ], + }), + { + code: ` +type Props = { a: string }; +declare function Foo(props: Props): never; +; + `, + filename: 'react.tsx', + errors: [ + { + messageId: 'anyAssignment', + line: 4, + column: 9, + endColumn: 17, + }, + ], + }, + ], +}); diff --git a/packages/typescript-estree/src/ts-estree/ts-estree.ts b/packages/typescript-estree/src/ts-estree/ts-estree.ts index 24486b974b3..caf979a3012 100644 --- a/packages/typescript-estree/src/ts-estree/ts-estree.ts +++ b/packages/typescript-estree/src/ts-estree/ts-estree.ts @@ -764,7 +764,7 @@ export interface AssignmentExpression extends BinaryExpressionBase { export interface AssignmentPattern extends BaseNode { type: AST_NODE_TYPES.AssignmentPattern; left: BindingName; - right?: Expression; + right: Expression; typeAnnotation?: TSTypeAnnotation; optional?: boolean; decorators?: Decorator[];