TypeScript ESLint: Unsafe assignment of an any value [Fix]
Last updated: Feb 29, 2024 Reading time · 5 min
# 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.
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.
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.
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 .
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
Borislav Hadzhiev
Web Developer
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 commented Mar 27, 2019 • edited
platinumazure commented Mar 27, 2019
- 👍 8 reactions
Sorry, something went wrong.
jordyvandomselaar commented Mar 29, 2019
mgol commented Apr 2, 2019
- ❤️ 1 reaction
bradzacher commented Apr 7, 2019
- 👍 2 reactions
phaux commented Apr 7, 2019 • edited
- 👍 1 reaction
bradzacher commented Apr 7, 2019 • edited
kilgarenone commented May 21, 2019
Bradzacher commented may 21, 2019.
fabb commented Aug 21, 2019
Platinumazure commented aug 21, 2019, fabb commented aug 22, 2019.
vanya2h commented Feb 10, 2020
Phaux commented feb 10, 2020, bradzacher commented feb 10, 2020.
No branches or pull requests
IMAGES
VIDEO
COMMENTS
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
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.
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.
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.
@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 ...
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
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.
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.
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.
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.
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 ...
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: -, +
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.
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:
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 ...
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.
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?
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 ...
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.
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
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.