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

Dey Code

@typescript-eslint/no-unsafe-assignment: Unsafe assignment of an any value – Typescript

Photo of author

Quick Fix: Make callGraph function generic and utilize TypeScript’s ReturnType to infer the type of the profile object in the defaultState method. Update the callGraph call in getGraphDetails to use the generic callGraph function.

The Solutions:

Solution 2: type the data at as low a level as possible.

It’s better to type the data at as low a level as possible, which in this case means the callGraph function:

By doing it that way, now callGraph ‘s return value is typed, and TS will therefore know that getGraphDetails and getGraphProfile both return that same type, since they ultimately just pass through the API response.

which pins should i take for i2c on arduino uno – Arduino

If/else else if in Jquery for a condition – Jquery

© 2024 deycode.com

no unsafe assignment typescript

Home » Tooling and Libraries » Typescript eslint no unsafe assignment unsafe assignment of an any value

Typescript eslint no unsafe assignment unsafe assignment of an any value

Introduction.

Typescript is a programming language that extends JavaScript by adding static types to it. It provides developers with the ability to catch errors and bugs during the development process, making the code more reliable and easier to maintain. However, there are certain situations where Typescript can still allow unsafe assignments of any value, which can lead to potential issues in the code.

Unsafe Assignment of an Any Value

One common scenario where unsafe assignment of an any value can occur is when using Typescript with ESLint. ESLint is a popular tool for identifying and reporting patterns found in JavaScript code. It can also be used with Typescript to enforce coding standards and catch potential issues.

However, ESLint’s default configuration does not include rules specific to Typescript. This means that it may not catch certain unsafe assignments of any value. For example, consider the following code:

In this example, we have a variable called myVariable of type any . The value assigned to it is a string. Then, we try to assign this value to a variable called myNumber of type number . Since myVariable is of type any , Typescript allows this assignment without any error or warning.

This can be problematic because we are assigning a string value to a variable that is supposed to hold a number. This can lead to unexpected behavior or errors later in the code when we try to perform operations on myNumber assuming it is a number.

Solution: Configuring ESLint for Typescript

To solve this issue, we need to configure ESLint to include rules specific to Typescript. This will enable ESLint to catch unsafe assignments of any value and provide warnings or errors accordingly.

To configure ESLint for Typescript, we need to install the necessary packages. Run the following command in your project directory:

Once the packages are installed, we need to update the ESLint configuration file (usually named .eslintrc or .eslintrc.json ) to include the Typescript-specific rules. Here’s an example configuration:

In this configuration, we specify the parser as @typescript-eslint/parser and include the @typescript-eslint plugin. We also extend the recommended ESLint rules and add the @typescript-eslint/no-unsafe-assignment rule, which catches unsafe assignments of any value.

After configuring ESLint for Typescript, running ESLint on the code example mentioned earlier will produce an error:

The error message will indicate that there is an unsafe assignment of an any value, preventing potential issues in the code.

Typescript is a powerful programming language that helps catch errors and bugs during development. However, it can still allow unsafe assignments of any value in certain situations. By configuring ESLint for Typescript and including the @typescript-eslint/no-unsafe-assignment rule, we can catch these unsafe assignments and prevent potential issues in our code.

  • No Comments
  • assignment , eslint , typescript , unsafe , value

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Table of Contents

Not stay with the doubts.

Typescript SOS

  • Privacy Overview
  • Strictly Necessary Cookies

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.

no-unsafe-call

Disallow calling a value with type any .

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

This rule requires type information to run.

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

Despite your best intentions, the any type can sometimes leak into your codebase. Calling an any -typed value as a function creates a potential type safety hole and source of bugs in your codebase.

This rule disallows calling any value that is typed as any .

Try this rule in the playground ↗

  • ❌ Incorrect

This rule is not configurable.

When Not To Use It ​

If your codebase has many existing any s 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.

Related To ​

  • no-explicit-any
  • no-unsafe-argument
  • no-unsafe-assignment
  • no-unsafe-member-access
  • no-unsafe-return

Resources ​

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

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

[no-unsafe-assignment] Unsafe Assignment on __dirname #2209

@RLashofRegas

RLashofRegas commented Jun 12, 2020

The text was updated successfully, but these errors were encountered:

@RLashofRegas

bradzacher commented Jun 12, 2020

Sorry, something went wrong.

@bradzacher

  • 👍 1 reaction

@github-actions

No branches or pull requests

@bradzacher

IMAGES

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

    no unsafe assignment typescript

  2. [Solved] @typescript-eslint/no-unsafe-assignment: Unsafe

    no unsafe assignment typescript

  3. TypeScript Function Types: A Beginner's Guide

    no unsafe assignment typescript

  4. TypeScript Tutorial

    no unsafe assignment typescript

  5. @typescript-eslint/no-unsafe-assignment throws error incorrectly

    no unsafe assignment typescript

  6. Question: Why do I get unsafe assignment of any error when the type is

    no unsafe assignment typescript

VIDEO

  1. Assignment Operators in Typescript

  2. Typescript Assignment Q no 11 to 15

  3. To do list ! Governor house ! Assignment !

  4. Hướng dẫn Assignment TypeScript

  5. Typescript 45 Questions Assignment Part 14

  6. TypeScript Nullable Type

COMMENTS

  1. no-unsafe-assignment

    no-unsafe-assignment. Disallow assigning a value with type any to variables and properties. Extending "plugin:@typescript-eslint/ recommended-type-checked " in an ESLint configuration enables this rule. This rule requires type information to run. The any type in TypeScript is a dangerous "escape hatch" from the type system.

  2. javascript

    TypeScript offers no real type safety anyway, just development-time type hints, and the TS inference is just so delightful! But yes, for a more complex solution, please declare your interfaces first, and make sure your server and client share/agree on them.

  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. node.js

    Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.Provide details and share your research! But avoid …. Asking for help, clarification, or responding to other answers.

  5. no-unsafe-argument

    no-unsafe-argument. Disallow calling a function with a value with type any. . Extending "plugin:@typescript-eslint/ recommended-type-checked " in an ESLint configuration enables this rule. 💭. This rule requires type information to run. The any type in TypeScript is a dangerous "escape hatch" from the type system.

  6. @typescript-eslint/no-unsafe-assignment: Unsafe assignment of an any

    Consider the following example: We have a function getGraphProfile() that fetches data from a graph API and we want to assign the response to a local object state.profile.However, the return type of getGraphProfile() is Promise<AxiosResponse<any>>, meaning that the data returned from the API is of type any.When we assign this any value to state.profile, TypeScript doesn't complain, but the ...

  7. Examples

    \n. 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

  8. @typescript-eslint/no-unsafe-assignment: Unsafe assignment of an any

    Quick Fix: Make callGraph function generic and utilize TypeScript's ReturnType to infer the type of the profile object in the defaultState method. Update the callGraph call in getGraphDetails to use the generic callGraph function.

  9. [no-unsafe-assignment/return] Relax restrictions to allow any ...

    In this regard, unknown and any are the same. The difference being that unknown ensures you don't do things that are unsafe. Not being able to convert past object is a known issue that they haven't solved just yet.

  10. [no-unsafe-assignment] [no-unsafe-call] [no-unsafe-return ...

    Thanks for the detailed reply! I think the "correct" solution to this problem is more strict options in TypeScript itself. It's a bit odd IMO that you need a separate tool to find lurking any when there's noImplicityAny.The rules that overlap with the compiler should be in the compiler.

  11. Typescript eslint no unsafe assignment unsafe assignment of an any

    Introduction Typescript is a programming language that extends JavaScript by adding static types to it. It provides developers with the ability to catch errors and bugs during the development process, making the code more reliable and easier to maintain. However, there are certain situations where Typescript can still allow unsafe assignments of any value, which […]

  12. no-unsafe-return

    no-unsafe-return. Disallow returning a value with type any from a function. . Extending "plugin:@typescript-eslint/ recommended-type-checked " in an ESLint configuration enables this rule. 💭. This rule requires type information to run. The any type in TypeScript is a dangerous "escape hatch" from the type system.

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

    Expected Result. 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-assignment] False positive of destructuring an

    The assignment const [bar] = arg; causes Unsafe array destructuring of an `any` array value. While this line is indeed an array destructuring of any array value, I don't think this is unsafe. The type guard isZero(arg[0]) guarantees that the first element of arg is of type 0 , so is bar (and the compiler infers as such).

  15. @typescript-eslint/no-unsafe-assignment

    I use app insights library in my angular project. And I use eslint to lint the code which really helps find some weird bugs: @Injectable({ providedIn: "root" }) export class AppInsightsService {. appInsights: ApplicationInsights; constructor() {. this.appInsights = new ApplicationInsights({ // ====> HERE. config: {.

  16. New set of rules: `no-unsafe-*` · Issue #791 · typescript-eslint

    (feat(eslint-plugin): add rule no-unsafe-assignment #1694) Considering also handling x += 1, etc. Probably should. Using any in arithmetic expression. At this point, this should be implicitly handled by any of the previous rules. const x = 1 * any caught by no-unsafe-assignment; return 1 * any caught by no-unsafe-return

  17. no-unsafe-enum-comparison

    no-unsafe-enum-comparison. Disallow comparing an enum value with a non-enum value. Extending "plugin:@typescript-eslint/ recommended-type-checked " in an ESLint configuration enables this rule. Some problems reported by this rule are manually fixable by editor suggestions. This rule requires type information to run.

  18. no-unsafe-call

    The any type in TypeScript is a dangerous "escape hatch" from the type system. Using any disables many type checking rules and is generally best used only as a last resort or when prototyping code.. Despite your best intentions, the any type can sometimes leak into your codebase. Calling an any-typed value as a function creates a potential type safety hole and source of bugs in your codebase.

  19. [no-unsafe-assignment] Unsafe Assignment on __dirname #2209

    No linting errors are flagged on __dirname because I set env.node=true. Actual Result Received Unsafe assignment of any value. on the __dirname assignment. Additional Info I know I must be doing something wrong, so this may be more of a question, but this seems like the best place to get help, thanks :) Versions