TypeScript ESLint: Unsafe assignment of an any value [Fix]

avatar

Last updated: Feb 29, 2024 Reading time · 5 min

banner

# TypeScript ESLint: Unsafe assignment of an any value

The error "@typescript-eslint/no-unsafe-assignment: Unsafe assignment of an any value." occurs when you assign a value with a type of any to a variable or a property.

To solve the error, set the variable to a specific type or disable the ESLint rule.

Here are some examples of when the ESLint error is raised.

All of the assignments above cause the error because the ESLint rule prevents you from assigning a value with an any type to a variable.

The any type effectively turns off type checking and should be used sparingly.

This article addresses 2 similar ESLint errors:

  • @typescript-eslint/no-unsafe-assignment: Unsafe assignment of an any value.
  • Unexpected any. Specify a different type. eslint@typescript-eslint/no-explicit-any

# Disabling the @typescript-eslint/no-unsafe-assignment ESLint rule

One way to get around the ESLint error is to disable the rule.

For example, the following comment disables the rule for 1 line.

disabling the ts eslint no unsafe assignment rule

If you need to disable the @typescript-eslint/no-explicit-any rule for a single line, use the following comment.

If you need to disable multiple rules for a line, separate them by a comma.

If you need to disable the rule for the entire file, use the following comment.

If you need to disable the @typescript-eslint/no-explicit-any rule for the entire file, use the following comment instead.

You can disable both rules for the entire file by using the following comment.

If you want to disable the rules globally, add the following 2 rules to your .eslintrc.js file.

disable the two rules

If you use a .eslintrc.json file, make sure to double-quote the keys and values.

# Setting the variable or property to unknown instead of any

Alternatively, you can set the variable or property to unknown to resolve the ESLint error.

setting the variable property to unknown instead of any

The unknown type is the type-safe counterpart of any .

When working with the unknown type, we basically tell TypeScript that we're going to get this value, but we don't know its type.

We are going to check with a couple of if statements to track the type down and use it safely.

I have written a detailed guide on how to check the type of a variable in TypeScript .

When using the unknown type, you have to use an if statement as a type guard to check the type of the variable before you are able to use any type-specific methods (e.g. string, array, object, etc).

# The error commonly occurs when parsing a JSON string

The error commonly occurs when parsing a JSON string with the JSON.parse() method.

The result variable stores a value of any type because TypeScript doesn't know the type of the value that is being parsed.

One way to resolve the issue is to use a type predicate .

using type predicate to solve the error

The value is Employee syntax is called a type predicate.

Our function basically checks if the passed-in value is compatible with an object of type Employee .

Notice that in the if block in which we called the isAnEmployee() function, the parsed variable is typed as Employee and we can access the id and name properties without getting TypeScript or ESLint errors.

I've written a detailed guide on how to check if a value is an object .

# Resolve the issue by typing the variable explicitly

You can also resolve the issue by typing the variable explicitly and removing the any type.

Here is an example of typing an object.

And here is an example of typing an array of objects.

You might have to use a type assertion, e.g. when parsing a JSON string.

In some rare cases, you might have to widen the type to unknown before using a type assertion to set a more specific type.

I've written detailed guides on:

  • How to initialize a typed Empty Object in TypeScript
  • Declare an Empty Array for a typed Variable in TypeScript
  • How to add Elements to an Array in TypeScript
  • Check if an Array contains a Value in TypeScript
  • Check if a Value is an Array (of type) in TypeScript
  • How to declare an Array of Objects in TypeScript
  • How to declare a Two-dimensional Array in TypeScript
  • Declare Array of Numbers, Strings or Booleans in TypeScript
  • Create an Object based on an Interface in TypeScript
  • Create a Type from an object's Keys or Values in TypeScript
  • ESLint: Expected property shorthand object-shorthand [Fixed]
  • 'X' should be listed in the project's dependencies, not devDependencies
  • ESLint: Unexpected lexical declaration in case block [Fixed]
  • ESLint couldn't find the config 'prettier' to extend from
  • Import in body of module reorder to top eslint import/first
  • ESLint: A form label must be associated with a control

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

no-unsafe-negation

Disallow negating the left operand of relational operators

Using the recommended config from @eslint/js in a configuration file enables this rule

Some problems reported by this rule are manually fixable by editor suggestions

Just as developers might type -a + b when they mean -(a + b) for the negative of a sum, they might type !key in object by mistake when they almost certainly mean !(key in object) to test that a key is not in an object. !obj instanceof Ctor is similar.

Rule Details

This rule disallows negating the left operand of the following relational operators:

  • in operator .
  • instanceof operator .

Examples of incorrect code for this rule:

Examples of correct code for this rule:

For rare situations when negating the left operand is intended, this rule allows an exception. If the whole negation is explicitly wrapped in parentheses, the rule will not report a problem.

This rule has an object option:

  • "enforceForOrderingRelations": false (default) allows negation of the left-hand side of ordering relational operators ( < , > , <= , >= )
  • "enforceForOrderingRelations": true disallows negation of the left-hand side of ordering relational operators

enforceForOrderingRelations

With this option set to true the rule is additionally enforced for:

  • < operator.
  • > operator.
  • <= operator.
  • >= operator.

The purpose is to avoid expressions such as ! a < b (which is equivalent to (a ? 0 : 1) < b ) when what is really intended is !(a < b) .

Examples of additional incorrect code for this rule with the { "enforceForOrderingRelations": true } option:

When Not To Use It

If you don’t want to notify unsafe logical negations, then it’s safe to disable this rule.

Handled by TypeScript

It is safe to disable this rule when using TypeScript because TypeScript's compiler enforces this check.

This rule was introduced in ESLint v3.3.0.

  • Rule source
  • Tests source

no-unsafe-declaration-merging

Disallow unsafe declaration merging.

Extending "plugin:@typescript-eslint/ recommended " in an ESLint configuration enables this rule.

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.

Try this rule in the playground ↗

  • ❌ Incorrect

This rule is not configurable.

When Not To Use It ​

If your project intentionally defines classes and interfaces with unsafe declaration merging patterns, this rule might not be for you. You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.

Further Reading ​

  • Declaration Merging

Resources ​

  • Rule source
  • Test source
  • When Not To Use It
  • Further Reading

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

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

1:1 error Definition for rule '@typescript-eslint/no-unused-vars' was not found @typescript-eslint/no-unused-vars #379

@jordyvandomselaar

jordyvandomselaar commented Mar 27, 2019 • edited

@platinumazure

platinumazure commented Mar 27, 2019

  • 👍 8 reactions

Sorry, something went wrong.

@bradzacher

jordyvandomselaar commented Mar 29, 2019

@amio

mgol commented Apr 2, 2019

  • ❤️ 1 reaction

@armano2

bradzacher commented Apr 7, 2019

  • 👍 2 reactions

@phaux

phaux commented Apr 7, 2019 • edited

  • 👍 1 reaction

bradzacher commented Apr 7, 2019 • edited

@huruji

kilgarenone commented May 21, 2019

Bradzacher commented may 21, 2019.

@huan

fabb commented Aug 21, 2019

Platinumazure commented aug 21, 2019, fabb commented aug 22, 2019.

@vanya2h

vanya2h commented Feb 10, 2020

Phaux commented feb 10, 2020, bradzacher commented feb 10, 2020.

@typescript-eslint

No branches or pull requests

@fabb

IMAGES

  1. How To Refuse an Unsafe Patient Assignment as a Nurse

    definition for rule 'no unsafe assignment' was not found

  2. Understanding Unsafe Act and Unsafe Condition in the Workplace

    definition for rule 'no unsafe assignment' was not found

  3. Unsafe Working Conditions: Recognize, Refuse, and Report

    definition for rule 'no unsafe assignment' was not found

  4. Can You Refuse An Unsafe Assignment?

    definition for rule 'no unsafe assignment' was not found

  5. [no-unsafe-assignment] fails to infer the type from class properties

    definition for rule 'no unsafe assignment' was not found

  6. What is Unsafe Act and Unsafe Conditions in the workplace

    definition for rule 'no unsafe assignment' was not found

VIDEO

  1. DANGEROUS LAW NO 1 || #shorts

  2. UNSAFE Conditions vs UNSAFE Acts (Near Miss vs Incident PART 2)

  3. [TWO TONES] Firefighters Battle Lorry Fire on M25 Motorway!

  4. How to Fix ERR UNKNOWN URL SCHEME on Windows 10/11

  5. Building on an unsafe foundation

  6. Arduino: Arduino Robot. a function-definition is not allowed here before '{' token

COMMENTS

  1. javascript

    I'm trying to add TypeScript compilation to an existing Javascript project. AFAIK this is supposed to be possible (even easy), and you can incrementally spread TS through the codebase. Unfortunately

  2. no-unsafe-assignment

    Options . This rule is not configurable. When Not To Use It . If your codebase has many existing anys or areas of unsafe code, it may be difficult to enable this rule.It may be easier to skip the no-unsafe-* rules pending increasing type safety in unsafe areas of your project. You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.

  3. TypeScript ESLint: Unsafe assignment of an any value [Fix]

    Our function basically checks if the passed-in value is compatible with an object of type Employee.. Notice that in the if block in which we called the isAnEmployee() function, the parsed variable is typed as Employee and we can access the id and name properties without getting TypeScript or ESLint errors.. I've written a detailed guide on how to check if a value is an object.

  4. Rules Reference

    Rules Reference. Rules in ESLint are grouped by type to help you understand their purpose. Each rule has emojis denoting: Using the recommended config from @eslint/js in a configuration file enables this rule. Some problems reported by this rule are automatically fixable by the --fix command line option.

  5. Overview

    @typescript-eslint/ no-unsafe-assignment ... @typescript-eslint/ no-unsafe-unary-minusRequire unary negation to take a number: ... Extension Rules Some core ESLint rules do not support TypeScript syntax: either they crash, ignore the syntax, or falsely report against it. In these cases, we create what we call an "extension rule": a rule within ...

  6. Examples

    If your codebase has many existing anys or areas of unsafe code, it may be difficult to enable this rule.\nIt may be easier to skip the no-unsafe-* rules pending increasing type safety in unsafe areas of your project.\nYou might consider using ESLint disable comments for those specific situations instead of completely disabling this rule. \n

  7. typescript-eslint/no-unsafe-assignment error with dependencies of

    The foo variable might not be giving any type errors (and I find it odd that enabling noImplicitAny doesn't cause any of those to be reported), but it doesn't have any known properties in TypeScript-land.

  8. New eslint errors with the @typescript-eslint/no-unsafe-* rules

    But of course situations may arise when we may want to edit a rule to generate warnings, instead of errors. Type checking is a trade off: we loose convenience in exchange for safety. But in the end it's the team or developer who decides which rules eslint should enforce.

  9. Examples

    The any type in TypeScript is a dangerous \"escape hatch\" from the type system.\nUsing any disables many type checking rules and is generally best used only as a last resort or when prototyping code.

  10. no-unsafe-member-access

    Options . This rule is not configurable. When Not To Use It . If your codebase has many existing anys or areas of unsafe code, it may be difficult to enable this rule.It may be easier to skip the no-unsafe-* rules pending increasing type safety in unsafe areas of your project. You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.

  11. typescript

    5. I'm using TSLint to lint my Angular TypeScript code. I enabled no-unsafe-any rule, as it seems like a good rule to me to never assume anything about properties of type any. The problem is the rule reports errors on some of my code, which I'm unable to fix in any way other than disabling the rule. Example of a code that's invalid according to ...

  12. no-unsafe-optional-chaining

    Options. This rule has an object option: disallowArithmeticOperators: Disallow arithmetic operations on optional chaining expressions (Default false).If this is true, this rule warns arithmetic operations on optional chaining expressions, which possibly result in NaN.; disallowArithmeticOperators. With this option set to true the rule is enforced for:. Unary operators: -, +

  13. [no-unsafe-assignment] fails to infer the type from class properties

    The no-unsafe-assignment rule is flagging the creation of the Map in the constructor as being unsafe, claiming it can accept any types, even though the type is enforced by the events property in the class. Actual Result. I see no logical reason why this should be considered an unsafe assignment when the type is clearly enforced by the property.

  14. no-unsafe-negation

    Just as developers might type -a + b when they mean -(a + b) for the negative of a sum, they might type !key in object by mistake when they almost certainly mean !(key in object) to test that a key is not in an object. !obj instanceof Ctor is similar. Rule Details. This rule disallows negating the left operand of the following relational operators:

  15. Eslint Typescript "No Implicit Any" rule

    There are a number of no-unsafe-* rules that have been implemented in TypeScript-ESLint:. no-unsafe-call - forbids calling an expression typed as any; no-unsafe-member-access - forbids using any as a member name; no-unsafe-argument - forbids passing any as a function parameter; no-unsafe-assignment - forbids using any in an assignment; These are all standalone rules, but they've also all been ...

  16. New set of rules: no-unsafe-* #791

    These rules are all implemented - one final case remains to be implemented: no-unsafe-argument to catch when you're passing any into an argument. (See #791 (comment)) Create a rule which uses type information to determine when you're inadvertently breaking type safety by using an any, potentially without knowing.

  17. eslint "Definition for rule 'no-explicit-any' was not found" always shown

    Now, for some reason unknown to me, every file starts with the warning/error: Line 1:1: Definition for rule 'no-explicit-any' was not found no-explicit-any, even if the file doesn't even have the any type, and even if the file is empty! It's an important rule, and I don't want to just ignore it. Is it a bug? Am I doing something wrong?

  18. [@typescript-eslint/no-unsafe-argument] Cannot seem to turn rule off

    I have tried restarting my IDE and the issue persists. I have updated to the latest version of the packages. I have read the FAQ and my problem is not listed. Repro // .eslintrc.js const { resolve ...

  19. no-unsafe-return

    Options . This rule is not configurable. When Not To Use It . If your codebase has many existing anys or areas of unsafe code, it may be difficult to enable this rule.It may be easier to skip the no-unsafe-* rules pending increasing type safety in unsafe areas of your project. You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.

  20. no-unsafe-declaration-merging

    This rule is not configurable. When Not To Use It If your project intentionally defines classes and interfaces with unsafe declaration merging patterns, this rule might not be for you. You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule. Further Reading Declaration Merging

  21. 1:1 error Definition for rule '@typescript-eslint/no-unused ...

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window.