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-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. 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 a function with an any typed argument creates a potential safety hole and source of bugs.

This rule disallows calling a function with any in its arguments. That includes spreading arrays or tuples with any typed elements as function arguments.

This rule also compares generic type argument types to ensure you don't pass an unsafe any in a generic position to a receiver that's expecting a specific type. For example, it will error if you pass Set<any> as an argument to a parameter declared as Set<string> .

Try this rule in the playground ↗

  • ❌ Incorrect

There are cases where the rule allows passing an argument of any to unknown .

Example of any to unknown assignment that are allowed:

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-assignment
  • no-unsafe-call
  • no-unsafe-member-access
  • no-unsafe-return

Resources ​

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

質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!.

TypeScriptは、マイクロソフトによって開発された フリーでオープンソースのプログラミング言語です。 TypeScriptは、JavaScriptの構文の拡張であるので、既存の JavaScriptのコードにわずかな修正を加えれば動作します。

Importした型定義でeslintのUnsafe assignment of an `any` value.が出てしまう

izumeeeel

投稿 2021/10/02 07:23

以下のファイルで型定義をして

以下のファイルでimportして使っているのですが、

以下のようなeslintエラーが出てしまいます。

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

(property) Expense.IFetchedExpense.updated_at: Date

エラー

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちら の条件を満たす必要があります。

guest

export = Expense の記法がよくないです。 以下のように修正すればよいかと。

ただ namespace を export すると利用側は Expense.IFetchedExpense Expense.IExpense のように名前空間から記載する必要があります。 他のインターフェイスと名前が重複しないのであれば、以下のように直接 interface を export するのがよいかと思います。

投稿 2021/10/03 06:51

gekijin

2021/10/08 01:51

質問の解決につながる回答をしましょう。 サンプルコードなど、より具体的な説明があると質問者の理解の助けになります。 また、読む側のことを考えた、分かりやすい文章を心がけましょう。

15分調べてもわからないことは teratailで質問しよう!

ただいまの回答率 85 . 47 %

質問をまとめることで 思考を整理して素早く解決

テンプレート機能で 簡単に質問をまとめる

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

Bug: object-shorthand loses type parameters when auto-fixing #18429

@aldeed

aldeed commented May 7, 2024

@aldeed

nzakas commented May 8, 2024

  • 🎉 1 reaction

Sorry, something went wrong.

@shulaoda

Successfully merging a pull request may close this issue.

@nzakas

IMAGES

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

    typescript eslint unsafe assignment of an any value

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

    typescript eslint unsafe assignment of an any value

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

    typescript eslint unsafe assignment of an any value

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

    typescript eslint unsafe assignment of an any value

  5. reactjs

    typescript eslint unsafe assignment of an any value

  6. typescript

    typescript eslint unsafe assignment of an any value

VIDEO

  1. 👀 Time to ditch eslint? #tutorial #typescript #webdevelopment #javascript #programming #reactjs

  2. Assignment Operators in Typescript

  3. TypeScript vs ESLint #typescript #javascript

  4. Use Destructuring Assignment to Pass an Object as a Function's Parameters (ES6) freeCodeCamp

  5. Unsafe Working Conditions

  6. Typescript 45 Questions Assignment Part 36

COMMENTS

  1. 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.

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

    Eric's point is valid, and you generally want to instantiate your objects (and return types from functions) based on a declared interface. But I also wanted to show you the amazing power of TS to work backwards, inferring an interface from an instance of an object or function.

  3. 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.

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

    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-explicit-any

    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. This rule reports on explicit uses of the any keyword as a type annotation. Preferable alternatives to any include: TypeScript's --noImplicitAny ...

  6. 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

  7. [@typescript-eslint/no-unsafe-assignment] False positive on any type

    Isn't that kind of the point? You shouldn't be passing an any typed thing anywhere, least of all into a place that's expecting a strictly typed value. That is inherently unsafe and will lead to hard-to-debug runtime errors.

  8. @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 ...

  9. Making TypeScript Truly "Strongly Typed"

    // Incorrect const formValues = JSON.parse(userInput); // ^ Unsafe assignment of an `any` value. Thanks to the no-unsafe-assignment rule, we can catch the any type even before passing formValues elsewhere. The fixing strategy remains the same: We can use type narrowing to provide a specific type to the variable's value.

  10. bobbyhadz/typescript-eslint-unsafe-assignment-of-an-any-value

    Alternatively, you can run the TypeScript project in watch mode, so that the TypeScript server is restarted every time you make a change and save. npm run dev The npm run dev command uses nodemon to watch for changes and restarts your TypeScript project every time you save (Ctrl + S).

  11. 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.

  12. r/typescript on Reddit: Question: Why do I get unsafe assignment of any

    There's a place in your custom-types library where you use INotification as if it was generic. Maybe that's causing problems with the way eslint interprets it.

  13. React Typescript

    ONLY in the href attr is value (the object) underlined red saying "ESLint: Unsafe assignment of an `any` value." while the property "link_href" and value.link_text is not underlined. The types: interface IColumnTypes extends ILink, IRecordValue {} type Partial<T> = { [A in keyof T]?:

  14. error Unsafe assignment of an any value #2011

    @adrai Thank you for reply. It's true that the errors can be resolved with that workaround, but what concerns me is whether the change from string type to any type aligns with the implementer's intention.

  15. 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.

  16. `styled` producing `Unsafe assignment of an `any` value` typescript

    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.

  17. typescript eslint

    When I run eslint on this, it complains that there's an unsafe assignment of an any value but I can't figure out how to make it happy. Would appreciate any insight on this. typescript-eslint

  18. Importした型定義でeslintのUnsafe assignment of an `any` value.が出てしまう

    TypeScriptは、マイクロソフトによって開発された フリーでオープンソースのプログラミング言語です。 TypeScriptは、JavaScriptの構文の拡張であるので、既存の JavaScriptのコードにわずかな修正を加えれば動作します。 ... Unsafe assignment of an any value.eslint@typescript ...

  19. [no-unsafe-assignment] False positive of destructuring an `any` array

    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).

  20. Bug: object-shorthand loses type parameters when auto-fixing

    Environment Node version: v18.19. npm version: v10.7.0 Local ESLint version: v8.57. (Currently used) Global ESLint version: Not found Operating System: darwin 23.4.0 What parser are you using? @typescript-eslint/parser What did you do?...

  21. Eslint will not run in github actions as I apparently put src folder

    ESLint couldn't find the config "prettier/@typescript-eslint" after relocating .eslintrc to parent 0 Cypress GitHub Actions Error: The cypress-ntlm-auth plugin must be loaded before using this method