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

Search icon

Making TypeScript Truly "Strongly Typed"

Read on Terminal Reader

Too Long; Didn't Read

People mentioned.

Mention Thumbnail

TypeScript claims to be a strongly typed programming language built on top of JavaScript, providing better tooling at any scale. However, TypeScript includes the any type, which can often sneak into a codebase implicitly and lead to a loss of many of TypeScript's advantages.

This article explores ways to take control of the any type in TypeScript projects. Get ready to unleash the power of TypeScript, achieving ultimate type safety and improving code quality.

Disadvantages of Using Any in TypeScript

TypeScript provides a range of additional tooling to enhance developer experience and productivity:

  • It helps catch errors early in the development stage.
  • It offers excellent auto-completion for code editors and IDEs.
  • It allows for easy refactoring of large codebases through fantastic code navigation tools and automatic refactoring.
  • It simplifies understanding of a codebase by providing additional semantics and explicit data structures through types.

However, as soon as you start using the any type in your codebase, you lose all the benefits listed above. The any type is a dangerous loophole in the type system, and using it disables all type-checking capabilities as well as all tooling that depends on type-checking. As a result, all the benefits of TypeScript are lost: bugs are missed, code editors become less useful, and more.

For instance, consider the following example:

In the code above:

  • You will miss auto-completion inside the parse function. When you type data. in your editor, you won't be given correct suggestions for the available methods for data .
  • In the first case, there is a TypeError: data.split is not a function error because we passed a number instead of a string. TypeScript is not able to highlight the error because any disables type checking.
  • In the second case, the res2 variable also has the any type. This means that a single usage of any can have a cascading effect on a large portion of a codebase.

Using any is okay only in extreme cases or for prototyping needs. In general, it is better to avoid using any to get the most out of TypeScript.

Where the Any Type Comes From

It's important to be aware of the sources of the any type in a codebase because explicitly writing any is not the only option. Despite our best efforts to avoid using the any type, it can sometimes sneak into a codebase implicitly.

There are four main sources of the any type in a codebase:

  • Compiler options in tsconfig.
  • TypeScript's standard library.
  • Project dependencies.
  • Explicit use of any in a codebase.

I have already written articles on Key Considerations in tsconfig and Improving Standard Library Types for the first two points. Please check them out if you want to improve type safety in your projects.

This time, we will focus on automatic tools for controlling the appearance of the any type in a codebase.

Stage 1: Using ESLint

ESLint is a popular static analysis tool used by web developers to ensure best practices and code formatting. It can be used to enforce coding styles and find code that doesn't adhere to certain guidelines.

ESLint can also be used with TypeScript projects, thanks to typesctipt-eslint plugin. Most likely, this plugin has already been installed in your project. But if not, you can follow the official getting started guide .

The most common configuration for typescript-eslint is as follows:

This configuration enables eslint to understand TypeScript at the syntax level, allowing you to write simple eslint rules that apply to manually written types in a code. For example, you can forbid the explicit use of any .

The recommended preset contains a carefully selected set of ESLint rules aimed at improving code correctness. While it's recommended to use the entire preset, for the purpose of this article, we will focus only on the no-explicit-any rule.

no-explicit-any

TypeScript's strict mode prevents the use of implied any , but it doesn't prevent any from being explicitly used. The no-explicit-any rule helps to prohibit manually writing any anywhere in a codebase.

The primary purpose of this rule is to prevent the use of any throughout the team. This is a means of strengthening the team's agreement that the use of any in the project is discouraged.

This is a crucial goal because even a single use of any can have a cascading impact on a significant portion of the codebase due to type inference . However, this is still far from achieving ultimate type safety.

Why no-explicit-any is Not Enough

Although we have dealt with explicitly used any , there are still many implied any within a project's dependencies, including npm packages and TypeScript's standard library.

Consider the following code, which is likely to be seen in any project:

Both variables pokemons and settings were implicitly given the any type. Neither no-explicit-any nor TypeScript's strict mode will warn us in this case. Not yet.

This happens because the types for response.json() and JSON.parse() come from TypeScript's standard library, where these methods have an explicit any annotation. We can still manually specify a better type for our variables, but there are nearly 1,200 occurrences of any in the standard library. It's nearly impossible to remember all the cases where any can sneak into our codebase from the standard library.

The same goes for external dependencies. There are many poorly typed libraries in npm, with most still being written in JavaScript. As a result, using such libraries can easily lead to a lot of implicit any in a codebase.

Generally, there are still many ways for any to sneak into our code.

Stage 2: Enhancing Type Checking Capabilities

Ideally, we would like to have a setting in TypeScript that makes the compiler complain about any variable that has received the any type for any reason. Unfortunately, such a setting does not currently exist and is not expected to be added.

We can achieve this behavior by using the type-checked mode of the typescript-eslint plugin. This mode works in conjunction with TypeScript to provide complete type information from the TypeScript compiler to ESLint rules. With this information, it is possible to write more complex ESLint rules that essentially extend the type-checking capabilities of TypeScript. For instance, a rule can find all variables with the any type, regardless of how any was obtained.

To use type-aware rules, you need to slightly adjust ESLint configuration:

To enable type inference for typescript-eslint , add parserOptions to ESLint configuration. Then, replace the recommended preset with recommended-type-checked . The latter preset adds about 17 new powerful rules. For the purpose of this article, we will focus on only 5 of them.

no-unsafe-argument

The no-unsafe-argument rule searches for function calls in which a variable of type any is passed as a parameter. When this happens, type-checking is lost, and all the benefits of strong typing are also lost.

For example, let's consider a saveForm function that requires an object as a parameter. Suppose we receive JSON, parse it, and obtain an any type.

When we call the saveForm function with this parameter, the no-unsafe-argument rule flags it as unsafe and requires us to specify the appropriate type for the value variable.

This rule is powerful enough to deeply inspect nested data structures within function arguments. Therefore, you can be confident that passing objects as function arguments will never contain untyped data.

The best way to fix the error is to use TypeScript’s type narrowing or a validation library such as Zod or Superstruct . For instance, let's write the parseFormValues function that narrows the precise type of parsed data.

Note that it is allowed to pass the any type as an argument to a function that accepts unknown , as there are no safety concerns associated with doing so.

Writing data validation functions can be a tedious task, especially when dealing with large amounts of data. Therefore, it is worth considering the use of a data validation library. For instance, with Zod, the code would look like this:

no-unsafe-assignment

The no-unsafe-assignment rule searches for variable assignments in which a value has the any type. Such assignments can mislead the compiler into thinking that a variable has a certain type, while the data may actually have a different type.

Consider the previous example of JSON parsing:

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.

no-unsafe-member-access and no-unsafe-call

These two rules trigger much less frequently. However, based on my experience, they are really helpful when you are trying to use poorly typed third-party dependencies.

The no-unsafe-member-access rule prevents us from accessing object properties if a variable has the any type, since it may be null or undefined .

The no-unsafe-call rule prevents us from calling a variable with the any type as a function, as it may not be a function.

Let's imagine that we have a poorly typed third-party library called untyped-auth :

The linter highlights two issues:

  • Calling the authenticate function can be unsafe, as we may forget to pass important arguments to the function.
  • Reading the name property from the userInfo object is unsafe, as it will be null if authentication fails.

The best way to fix these errors is to consider using a library with a strongly typed API. But if this is not an option, you can augment the library types yourself. An example with the fixed library types would look like this:

no-unsafe-return

The no-unsafe-return rule helps to not accidentally return the any type from a function that should return something more specific. Such cases can mislead the compiler into thinking that a returned value has a certain type, while the data may actually have a different type.

For instance, suppose we have a function that parses JSON and returns an object with two properties.

The parseForm function may lead to runtime errors in any part of the program where it is used, since the parsed value is not checked. The no-unsafe-return rule prevents such runtime issues.

Fixing this is easy by adding validation to ensure that the parsed JSON matches the expected type. Let's use the Zod library this time:

A Note About Performance

Using type-checked rules comes with a performance penalty for ESLint since it must invoke TypeScript's compiler to infer all the types. This slowdown is mainly noticeable when running the linter in pre-commit hooks and in CI, but it is not noticeable when working in an IDE. The type checking is performed once on IDE startup and then updates the types as you change the code.

It is worth noting that just inferring the types works faster than the usual invocation of the tsc compiler. For example, on our most recent project with about 1.5 million lines of TypeScript code, type checking through tsc takes about 11 minutes, while the additional time required for ESLint's type-aware rules to bootstrap is only about 2 minutes.

For our team, the additional safety provided by using type-aware static analysis rules is worth the tradeoff. On smaller projects, this decision is even easier to make.

Controlling the use of any in TypeScript projects is crucial for achieving optimal type safety and code quality. By utilizing the typescript-eslint plugin, developers can identify and eliminate any occurrences of the any type in their codebase, resulting in a more robust and maintainable codebase.

By using type-aware eslint rules, any appearance of the keyword any in our codebase will be a deliberate decision rather than a mistake or oversight. This approach safeguards us from using any in our own code, as well as in the standard library and third-party dependencies.

Overall, a type-aware linter allows us to achieve a level of type safety similar to that of statically typed programming languages such as Java, Go, Rust, and others. This greatly simplifies the development and maintenance of large projects.

I hope you have learned something new from this article. Thank you for reading!

Useful Links

  • Library: typescript-eslint
  • Article: Key Considerations in tsconfig
  • Article: Improving Standard Library Types
  • Docs: Type Narrowing in TypeScript
  • Docs: Type Inference in TypeScript
  • Library: Zod
  • Library: Superstruct

Mongo DB

About Author

Maksim Zemskov HackerNoon profile picture

THIS ARTICLE WAS FEATURED IN ...

typescript unsafe assignment

RELATED STORIES

Article Thumbnail

typescript unsafe assignment

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.

HatchJS Logo

HatchJS.com

Cracking the Shell of Mystery

Safely Assigning Any Values in TypeScript

Avatar

Unsafe Assignment of an Any Value

In JavaScript, the `any` type is a catch-all type that can be assigned to any other type. This can be useful for working with unknown or unexpected values, but it can also lead to errors if you’re not careful.

When you assign an `any` value to a variable, you’re essentially telling the JavaScript engine that you don’t care what type of value is stored in that variable. This can be dangerous because it can lead to unexpected behavior if you try to use the variable in a way that’s incompatible with its actual type.

For example, if you assign an `any` value to a variable that’s declared as a number, you might be able to get away with it for a while. But eventually, you’ll run into an error when you try to use the variable in a mathematical operation.

The `any` type can also be used to create objects that have properties of different types. This can be useful for creating generic functions or components that can work with different types of data. However, it’s important to be aware of the potential pitfalls of using the `any` type, and to use it only when you really need to.

In this article, we’ll take a closer look at the `any` type and explore some of the risks and benefits of using it. We’ll also discuss some best practices for using the `any` type safely.

| Unsafe Assignment of an Any Value | Description | Example | |—|—|—| | Occurs when an any value is assigned to a variable of a more specific type | This can lead to unexpected behavior, as the any value may contain data that is not compatible with the more specific type | let x: number = ‘123’; |

What is an any value?

An any value is a value that can be of any type. In TypeScript, any values are denoted by the keyword `any`. Any values are often used as a placeholder for values that have not yet been determined. For example, you might use an any value to represent the return value of a function that you don’t know the type of yet.

Any values can be dangerous because they can be used to circumvent type safety checks. For example, you could assign an any value to a variable of a specific type, and then the value could be cast to the wrong type, which could lead to errors.

Why is unsafe assignment of an any value a problem?

Unsafe assignment of an any value can lead to errors and unexpected behavior. For example, if an any value is assigned to a variable of a specific type, the value may be cast to the wrong type, which can lead to errors. For example, the following code will throw an error:

const x: number = ‘foo’; // Error: Type ‘string’ is not assignable to type ‘number’.

Unsafe assignment of an any value can also make it difficult to debug code, as it can be difficult to track down the source of the error. For example, if an any value is assigned to a variable of a specific type, and then the value is used in a calculation, it may be difficult to determine which value is causing the error.

How to avoid unsafe assignment of any values

There are a few ways to avoid unsafe assignment of any values.

  • Use type annotations. Type annotations can help you to catch errors at compile time. For example, the following code will not compile because the type of the `x` variable is not specified:

const x = ‘foo’; // Error: Variable ‘x’ is not assigned a type.

  • Use type guards. Type guards can help you to check the type of a value at runtime. For example, the following code uses a type guard to check if the `x` variable is a number:

const x = ‘foo’; if (typeof x === ‘number’) { // Do something with the number value of x. }

  • Use the `strict` flag. The `strict` flag can help you to catch errors that would otherwise be caught at runtime. For example, the following code will throw an error because the `x` variable is assigned to a value of the wrong type:

const x = ‘foo’; console.log(x.toFixed()); // Error: Property ‘toFixed’ does not exist on type ‘string’.

Unsafe assignment of any values can lead to errors and unexpected behavior. There are a few ways to avoid unsafe assignment of any values, including using type annotations, type guards, and the `strict` flag.

By following these tips, you can help to ensure that your code is safe and reliable.

3. How to avoid unsafe assignment of an any value?

Unsafe assignment of an any value occurs when you assign a value of type `any` to a variable of a specific type. This can lead to errors and unexpected behavior because the value of the `any` variable can be of any type, including types that are not compatible with the variable’s declared type.

To avoid unsafe assignment of an any value, you can use the following techniques:

  • Use type assertions to explicitly cast any values to the desired type. A type assertion is a way to tell the compiler that you know that a value is of a certain type, even if it is declared as `any`. You can use a type assertion to cast an any value to a specific type using the following syntax:

const anyValue = ‘foo’; const stringValue = anyValue as string;

  • Use the `typeof` operator to check the type of a value before assigning it to a variable of a specific type. The `typeof` operator returns a string that indicates the type of a value. You can use the `typeof` operator to check the type of a value before assigning it to a variable of a specific type. For example:

const anyValue = ‘foo’; if (typeof anyValue === ‘string’) { const stringValue = anyValue; }

  • Use the `instanceof` operator to check if a value is an instance of a specific class. The `instanceof` operator returns a boolean value that indicates whether a value is an instance of a specific class. You can use the `instanceof` operator to check if a value is an instance of a specific class before assigning it to a variable of that class. For example:

const anyValue = new Object(); if (anyValue instanceof Object) { const objectValue = anyValue; }

By following these tips, you can avoid unsafe assignment of any values and write more secure code.

4. Unsafe assignment of an any value is a dangerous practice that can lead to errors and unexpected behavior.

When you assign a value of type `any` to a variable of a specific type, the compiler does not perform any type checking. This means that the value of the `any` variable can be of any type, including types that are not compatible with the variable’s declared type. This can lead to errors and unexpected behavior when you try to use the variable.

For example, consider the following code:

const anyValue = ‘foo’; const numberValue = anyValue; console.log(numberValue); // Error: cannot convert string to number

In this code, the variable `anyValue` is assigned a string value. However, the variable `numberValue` is declared as a number. When you try to log the value of `numberValue`, you get an error because the compiler cannot convert the string value of `anyValue` to a number.

This is just one example of the problems that can occur when you unsafely assign an any value to a variable of a specific type. By following the tips in this article, you can avoid unsafe assignment of any values and write more secure code.

Unsafe assignment of an any value is a dangerous practice that can lead to errors and unexpected behavior. By following the tips in this article, you can avoid unsafe assignment of any values and write more secure code.

Q: What is an unsafe assignment of an any value?

An unsafe assignment of an any value occurs when a variable of type any is assigned a value of a different type. This can lead to errors and unexpected behavior.

Q: Why is it unsafe to assign an any value?

It is unsafe to assign an any value because it can lead to errors and unexpected behavior. When a variable of type any is assigned a value of a different type, the JavaScript engine has to make a guess about what type the value should be. This can lead to errors if the engine makes the wrong guess.

Q: What are some examples of unsafe assignments of any values?

Some examples of unsafe assignments of any values include:

  • `let x = any; x = “hello”;`
  • `let y = any; y = 123;`
  • `let z = any; z = [];`

In each of these examples, the variable `x`, `y`, and `z` are all of type any. When they are assigned values of different types, the JavaScript engine has to make a guess about what type the values should be. This can lead to errors if the engine makes the wrong guess.

Q: How can I avoid unsafe assignments of any values?

There are a few ways to avoid unsafe assignments of any values.

  • Use type assertions. A type assertion is a way to explicitly tell the JavaScript engine what type a value is. You can use a type assertion to cast a value of any type to a specific type. For example, the following code uses a type assertion to cast the value of the variable `x` to the type `string`:

let x = any; x = “hello”; console.log(typeof x); // “string”

  • Use the `instanceof` operator. The `instanceof` operator can be used to check if an object is an instance of a particular class or type. You can use the `instanceof` operator to check if a variable of type any is an instance of a specific type. For example, the following code uses the `instanceof` operator to check if the variable `x` is an instance of the `String` class:

let x = any; x = “hello”; if (x instanceof String) { console.log(“x is an instance of the String class”); }

  • Use the `typeof` operator. The `typeof` operator can be used to get the type of a value. You can use the `typeof` operator to check if a variable of type any is a certain type. For example, the following code uses the `typeof` operator to check if the variable `x` is a string:

let x = any; x = “hello”; if (typeof x === “string”) { console.log(“x is a string”); }

Q: What are the potential consequences of an unsafe assignment of an any value?

The potential consequences of an unsafe assignment of an any value include:

  • Errors. If the JavaScript engine makes the wrong guess about the type of a value, it can lead to errors. For example, if the engine guesses that a value of type any is a string, and then tries to perform a mathematical operation on that value, an error will be thrown.
  • Unexpected behavior. Even if the JavaScript engine makes the correct guess about the type of a value, it can still lead to unexpected behavior. For example, if the engine guesses that a value of type any is a string, and then tries to use that value in a way that is only valid for numbers, unexpected behavior can occur.

Q: How can I fix unsafe assignments of any values?

There are a few ways to fix unsafe assignments of any values.

  • Use type assertions. As mentioned above, you can use type assertions to explicitly tell the JavaScript engine what type a value is. This can help to prevent errors and unexpected behavior.
  • Use the `instanceof` operator. You can use the `instanceof` operator to check if a variable of type any is an instance of a specific type. This can help you to avoid using values of the wrong type in your code.
  • Use the `typeof` operator. You can use the `typeof` operator to check the type of a value. This can help you to avoid using values of the wrong type in your code.

Q: What are some best practices for avoiding unsafe assignments of any values?

unsafe assignment of an any value can be a dangerous practice that can lead to errors and security vulnerabilities. It is important to be aware of the risks associated with this practice and to use it only when absolutely necessary. When possible, it is best to use a type assertion to explicitly convert the any value to a specific type. This will help to prevent errors and ensure that your code is safe.

Here are some key takeaways from this discussion:

  • Unsafe assignment of an any value can occur when a variable of type any is assigned a value of a different type.
  • This can lead to errors and security vulnerabilities.
  • It is best to use a type assertion to explicitly convert the any value to a specific type when possible.
  • This will help to prevent errors and ensure that your code is safe.

Author Profile

Marcus Greenwood

Latest entries

  • December 26, 2023 Error Fixing User: Anonymous is not authorized to perform: execute-api:invoke on resource: How to fix this error
  • December 26, 2023 How To Guides Valid Intents Must Be Provided for the Client: Why It’s Important and How to Do It
  • December 26, 2023 Error Fixing How to Fix the The Root Filesystem Requires a Manual fsck Error
  • December 26, 2023 Troubleshooting How to Fix the `sed unterminated s` Command

Similar Posts

Splunk bin vs bucket: what’s the difference.

Splunk Bin vs Bucket: What’s the Difference? Splunk is a powerful tool for collecting, analyzing, and visualizing data. But what are bins and buckets, and how do they differ? In this article, we’ll take a closer look at bins and buckets, and we’ll discuss how they’re used in Splunk. We’ll also provide some tips on…

Translate err_unknown_url_scheme from German to English

Translate Err_Unknown_URL_Scheme from German Have you ever encountered the error message “err_unknown_url_scheme” on your German-language computer? If so, you’re not alone. This error message is a common one, and it can be caused by a variety of factors. In this article, we’ll discuss what the error message means, how to fix it, and how to…

Can You Put Le Creuset in the Microwave? (The Answer Might Surprise You!)

Can You Put Le Creuset in the Microwave? Le Creuset is a popular brand of cast iron cookware known for its durability and stylish design. But can you put Le Creuset in the microwave? The answer is: yes, you can put Le Creuset in the microwave, but there are a few things you need to…

Why is Eclipse not showing suggestions?

Have you ever been coding in Eclipse and suddenly realized that the code completion suggestions have stopped working? It can be a frustrating experience, especially if you’re in the middle of a complex project. In this article, we’ll explore some of the reasons why your Eclipse code completion might not be working, and we’ll provide…

Unexpected any. Specify a different type

Unexpected Any. Specify a Different Type Have you ever been working on a JavaScript project and been surprised by a `TypeError` that you couldn’t explain? If so, you’re not alone. The `any` type can be a source of errors, especially when you’re not expecting it. In this article, we’ll take a look at what the…

How Long Does Clamato Juice Last After Opening?

Clam juice is a popular ingredient in many cocktails and dishes, but how long is it good for after opening? In this article, we’ll explore the shelf life of clamato juice, including how to store it properly and how to tell if it’s gone bad. We’ll also provide some tips on how to use up…

  • Datadog Site
  • Serverless for AWS Lambda
  • Autodiscovery
  • Datadog Operator
  • APM Tracing
  • Assigning Tags
  • Unified Service Tagging
  • Service Catalog
  • Session Replay
  • Continuous Testing
  • Browser Tests
  • Private Locations
  • Incident Management
  • Database Monitoring
  • Cloud Security Management
  • Software Composition Analysis
  • Workflow Automation
  • CI Visibility
  • Test Visibility
  • Intelligent Test Runner
  • Learning Center
  • Standard Attributes
  • Amazon Linux
  • Oracle Linux
  • Rocky Linux
  • From Source
  • Architecture
  • Supported Platforms
  • Advanced Configurations
  • Configuration Files
  • Status Page
  • Network Traffic
  • Proxy Configuration
  • FIPS Compliance
  • Dual Shipping
  • Secrets Management
  • Remote Configuration
  • Fleet Automation
  • Upgrade the Agent
  • Container Hostname Detection
  • Agent Flare
  • Agent Check Status
  • Permission Issues
  • Integrations Issues
  • Site Issues
  • Autodiscovery Issues
  • Windows Container Issues
  • Agent Runtime Configuration
  • High CPU or Memory Consumption
  • Data Security
  • Getting Started
  • OTLP Metrics Types
  • Configuration
  • Integrations
  • Resource Attribute Mapping
  • Metrics Mapping
  • Infrastructure Host Mapping
  • Hostname Mapping
  • Service-entry Spans Mapping
  • Ingestion Sampling
  • OTLP Ingestion by the Agent
  • W3C Trace Context Propagation
  • OpenTelemetry API Support
  • Correlate RUM and Traces
  • Correlate Logs and Traces
  • Troubleshooting
  • Visualizing OTLP Histograms as Heatmaps
  • Migrate to OpenTelemetry Collector version 0.95.0+
  • Producing Delta Temporality Metrics
  • Sending Data from OpenTelemetry Demo
  • OAuth2 in Datadog
  • Authorization Endpoints
  • Datagram Format
  • Unix Domain Socket
  • High Throughput Data
  • Data Aggregation
  • DogStatsD Mapper
  • Writing a Custom Agent Check
  • Writing a Custom OpenMetrics Check
  • Create an Agent-based Integration
  • Create an API Integration
  • Create a Log Pipeline
  • Integration Assets Reference
  • Build a Marketplace Offering
  • Create a Tile
  • Create an Integration Dashboard
  • Create a Recommended Monitor
  • Create a Cloud SIEM Detection Rule
  • OAuth for Integrations
  • Install Agent Integration Developer Tool
  • Submission - Agent Check
  • Submission - DogStatsD
  • Submission - API
  • JetBrains IDEs
  • Visual Studio
  • Enterprise Configuration
  • Account Management
  • Components: Common
  • Components: Azure
  • Components: AWS
  • AWS Accounts
  • Azure Accounts
  • Dashboard List
  • Interpolation
  • Correlations
  • Template Variables
  • Public Dashboards
  • Share Graphs
  • Scheduled Reports
  • Configure Monitors
  • Recommended Monitors
  • Audit Trail
  • Error Tracking
  • Integration
  • Live Process
  • Network Performance
  • Process Check
  • Real User Monitoring
  • Service Check
  • Search Monitors
  • Monitor Status
  • Check Summary
  • Monitor Settings
  • Monitor Quality
  • Host and Container Maps
  • Infrastructure List
  • Container Images View
  • Orchestrator Explorer
  • Kubernetes Resource Utilization
  • Increase Process Retention
  • Cloud Resources Schema
  • Metric Type Modifiers
  • Historical Metrics Ingestion
  • Submission - Powershell
  • OTLP Metric Types
  • Metrics Types
  • Distributions
  • Metrics Units
  • Advanced Filtering
  • Metrics Without Limits™
  • Impact Analysis
  • Faulty Deployment Detection
  • Managing Incidents
  • Natural Language Querying
  • Navigate the Service Catalog
  • Investigate a Service
  • Create Entries
  • Import Entries from Datadog
  • Import Entries from Integrations
  • Manage Entries
  • Service Definitions
  • Service Scorecards
  • Software Templates
  • Troubleshooting and Best Practices
  • Exploring APIs
  • Assigning Owners
  • Monitoring APIs
  • Adding Entries to API Catalog
  • Adding Metadata to APIs
  • API Catalog API
  • Endpoint Discovery from APM
  • Issue States
  • Regression Detection
  • Default Grouping
  • Custom Grouping
  • Identify Suspect Commits
  • Monitor-based SLOs
  • Metric-based SLOs
  • Time Slice SLOs
  • Error Budget Alerts
  • Burn Rate Alerts
  • OOTB Dashboard
  • Incident Details
  • Incident Settings
  • Incident Analytics
  • Datadog Clipboard
  • Ingest Events
  • Arithmetic Processor
  • Date Remapper
  • Category Processor
  • Grok Parser
  • Lookup Processor
  • Service Remapper
  • Status Remapper
  • String Builder Processor
  • Navigate the Explorer
  • Customization
  • Notifications
  • Saved Views
  • Triaging & Notifying
  • View and Manage
  • Create notifications and tickets
  • Create a Case
  • Build Workflows
  • Authentication
  • Trigger Workflows
  • Workflow Logic
  • Data Transformation
  • HTTP Requests
  • Private Action Credentials
  • Save and Reuse Actions
  • Connections
  • Actions Catalog
  • HTTP Request
  • JavaScript Expressions
  • Embedded Apps
  • Log collection
  • Tag extraction
  • Data Collected
  • Installation
  • Further Configuration
  • Prometheus & OpenMetrics
  • Control plane monitoring
  • Data collected
  • Data security
  • Commands & Options
  • Cluster Checks
  • Endpoint Checks
  • Admission Controller
  • AWS Fargate
  • Duplicate hosts
  • Cluster Agent
  • HPA and Metrics Provider
  • Lambda Metrics
  • Distributed Tracing
  • Log Collection
  • Advanced Configuration
  • Continuous Profiler
  • Securing Functions
  • Deployment Tracking
  • OpenTelemetry
  • Libraries & Integrations
  • Enhanced Metrics
  • Linux - Code
  • Linux - Container
  • Windows - Code
  • Azure Container Apps
  • Google Cloud Run
  • Overview Page
  • Network Analytics
  • Network Map
  • DNS Monitoring
  • SNMP Metrics
  • NetFlow Monitoring
  • Device Topology Map
  • Google Cloud
  • Confluent Cloud
  • Custom Costs
  • Datadog Costs
  • Tag Pipelines
  • Cost Recommendations
  • Cost Monitors
  • APM Terms and Concepts
  • Automatic Instrumentation
  • Custom Instrumentation
  • Library Compatibility
  • Library Configuration
  • Configuration at Runtime
  • Trace Context Propagation
  • Serverless Application Tracing
  • Proxy Tracing
  • Span Tag Semantics
  • Trace Metrics
  • Runtime Metrics
  • Ingestion Mechanisms
  • Ingestion Controls
  • Generate Metrics
  • Trace Retention
  • Usage Metrics
  • Correlate DBM and Traces
  • Correlate Synthetics and Traces
  • Correlate Profiles and Traces
  • Search Spans
  • Query Syntax
  • Span Facets
  • Span Visualizations
  • Trace Queries
  • Request Flow Map
  • Service Page
  • Resource Page
  • Service Map
  • APM Monitors
  • Expression Language
  • Error Tracking Explorer
  • Exception Replay
  • Tracer Startup Logs
  • Tracer Debug Logs
  • Connection Errors
  • Agent Rate Limits
  • Agent APM metrics
  • Agent Resource Usage
  • Correlated Logs
  • PHP 5 Deep Call Stacks
  • .NET diagnostic tool
  • APM Quantization
  • Supported Language and Tracer Versions
  • Profile Types
  • Profile Visualizations
  • Investigate Slow Traces or Endpoints
  • Compare Profiles
  • Agent Integration Overhead
  • Setup Architectures
  • Self-hosted
  • Google Cloud SQL
  • Autonomous Database
  • MongoDB Atlas
  • Connecting DBM and Traces
  • Exploring Database Hosts
  • Exploring Query Metrics
  • Exploring Query Samples
  • Schema Tracking
  • Data Jobs Monitoring
  • Monitoring Page Performance
  • Monitoring Performance Vitals
  • Monitoring Resource Performance
  • Collecting Browser Errors
  • Tracking User Actions
  • Frustration Signals
  • Crash Reporting
  • Mobile Vitals
  • Web View Tracking
  • Integrated Libraries
  • Supported Versions
  • Generate Custom Metrics
  • Connect RUM and Traces
  • Search RUM Events
  • Search Syntax
  • Watchdog Insights for RUM
  • Feature Flag Tracking
  • Track Browser Errors
  • Track Mobile Errors
  • User Retention
  • Funnel Analysis
  • Sankey Diagrams
  • Segmentation
  • Multistep API Testing
  • Recording Steps
  • Browser Testing Results
  • Advanced Options for Steps
  • Authentication in Browser Testing
  • Mobile App Testing
  • Testing Steps
  • Testing Results
  • Test Coverage
  • Connect APM
  • Results Explorer
  • Testing Multiple Environments
  • Testing With Proxy, Firewall, or VPN
  • Azure DevOps Extension
  • CircleCI Orb
  • GitHub Actions
  • Bitrise (Upload Application)
  • Bitrise (Run Tests)
  • AWS CodePipeline
  • Custom Commands
  • Custom Tags and Measures
  • Custom Pipelines API
  • Search and Manage
  • Search Pipeline Executions
  • CI Providers
  • Java and JVM Languages
  • JavaScript and TypeScript
  • JUnit Report Uploads
  • Tests in Containers
  • Search Test Runs
  • Developer Workflows
  • Code Coverage
  • Instrument Browser Tests with RUM
  • Instrument Swift Tests with RUM
  • Early Flake Detection
  • Auto Test Retries
  • Correlate Logs and Tests
  • How It Works
  • CircleCI Orbs
  • Generic CI Providers
  • Static Analysis (SAST) Rules
  • GitHub Pull Requests
  • IDE Plugins
  • APM Deployment Tracking
  • Suppressions
  • Security Inbox
  • Threat Intelligence
  • Account Takeover Protection
  • Content Packs
  • Log Detection Rules
  • Signal Correlation Rules
  • Security Signals
  • Investigator
  • Historical Jobs
  • Entities and Risk Scoring
  • Supported Deployment Types
  • Cloud Accounts
  • Agentless Scanning
  • CloudTrail Logs
  • Source Code Integrations
  • Supported Linux Distributions
  • Detection Rules
  • Investigate Security Signals
  • Investigate Agent Events
  • Creating Agent Rule Expressions
  • CWS Events Formats
  • Manage Compliance Rules
  • Create Custom Rules
  • Manage Compliance Posture
  • Explore Misconfigurations
  • Signals Explorer
  • Identity Risks
  • Hosts and Containers Compatibility
  • Compatibility Matrix
  • Mute Issues
  • Automate Security Workflows
  • Create Jira Issues
  • Severity Scoring
  • Vulnerabilities
  • Terms and Concepts
  • Using Single Step Instrumentation
  • Using Datadog Tracing libraries
  • Enabling ASM for Serverless
  • Code Security
  • Attack Summary
  • Attacker Explorer
  • Custom Detection Rules
  • Exploit Prevention
  • In-App WAF Rules
  • Trace Qualification
  • User Monitoring and Protection
  • API Security Inventory
  • Core Concepts
  • Trace an LLM Application
  • Auto Instrumentation
  • Submit Evaluations
  • Datadog Agent
  • HTTP Client
  • Splunk HTTP Event Collector
  • Splunk Forwarders (TCP)
  • Sumo Logic Hosted Collector
  • Update Existing Pipelines
  • Best Practices for Scaling Observability Pipelines
  • React Native
  • Other Integrations
  • Pipeline Scanner
  • Attributes and Aliasing
  • Rehydrate from Archives
  • PCI Compliance
  • Connect Logs and Traces
  • Search Logs
  • Advanced Search
  • Transactions
  • Log Side Panel
  • Watchdog Insights for Logs
  • Track Browser and Mobile Errors
  • Track Backend Errors
  • Manage Data Collection
  • Switching Between Orgs
  • User Management
  • Login Methods
  • Custom Organization Landing Page
  • Service Accounts
  • IP Allowlist
  • Cross-Organization Visibility
  • Granular Access
  • Permissions
  • User Group Mapping
  • Active Directory
  • API and Application Keys
  • Team Management
  • Multi-Factor Authentication
  • Safety Center
  • Cost Details
  • Usage Details
  • Product Allotments
  • Multi-org Accounts
  • Log Management
  • Synthetic Monitoring
  • HIPAA Compliance
  • Library Rules
  • Investigate Sensitive Data Issues
  • Regular Expression Syntax

Avoid assigning a value with type any

ID: typescript-best-practices/no-unsafe-assignment

Language: TypeScript

Severity: Warning

Category: Error Prone

Description

The  any  type in TypeScript is dangerously broad, leading to unexpected behavior. Using  any  should be avoided.

Non-Compliant Code Examples

Compliant code examples.

Seamless integrations. Try Datadog Code Analysis

Try this rule and analyze your code with Datadog Code Analysis

How to use this rule.

2 : - typescript-best-practices # Rules to enforce TypeScript best practices.
  • Create a static-analysis.datadog.yml with the content above at the root of your repository
  • Use our free IDE Plugins or add Code Analysis scans to your CI pipelines
  • Get feedback on your code

For more information, please read the Code Analysis documentation

VS Code Extension

Identify code vulnerabilities directly in your VS Code editor

JetBrains Plugin

Identify code vulnerabilities directly in JetBrains products

Use Datadog Code Analysis to catch code issues at every step of your development process

Request a personalized demo

Get started with datadog.

typescript unsafe assignment

  • See all results

Typescript-Eslint No-Unsafe-Assignment: Unsafe Assignment Of An Any Value

Typescript-Eslint No-Unsafe-Assignment: Unsafe Assignment Of An Any Value

Table of Contents

Introduction

To avoid a Typescript-Eslint No-Unsafe-Assignment warning, ensure to assign accurate types to your variables rather than deploying the ‘any’ value, promoting secure programming mechanics and enhancing code readability.

Quick Summary

When discussing Typescript-Eslint’s `no-unsafe-assignment` rule in conjunction with the “Any” value, it is crucial to understand firstly what these components are individually as well, and subsequently how they interact with each other.

Consider firstly, ‘Typescript’: an open-source language developed by Microsoft that brings static type-checking to JavaScript. It helps spot bugs early by providing types, interfaces, and type inference.

Next, we have ‘eslint’. ESLint is a tool for identifying and reporting on patterns in JavaScript. ESLint’s `no-unsafe-assignment` rule, specifically, guards against the assignment of values from unsafe sources or of mismatched types which could potentially lead to bugs.

The ‘Any’ value, most crucial amongst our trio, represents any JavaScript value, allowing you to opt-out of type-checking. However, its misuse can lead to potential problems and difficult-to-debug code.

Component Description/th>
Typescript An open-source programming language developed by Microsoft, that adds static types succinctly to JavaScript, aiding in code reliability.
Eslint No-Unsafe-Assignment Rule A rule in ESLint that warns programmers about assignments that might potentially cause bugs due to unsafe sources or mismatches in type.
Any Value A type in TypeScript that signifies any possible JavaScript value. While it allows some flexibility, overuse or misuse can lead type-checking errors and problematic code.

Now let’s discuss briefly how these interact: while Typescript’s strong typing significantly reduces the likelihood of runtime errors, ‘Any’ types can circumvent this advantage. If you assign an ‘Any’ type to a variable, Typescript no longer checks its type, potentially leading to bugs. Hence, the `no-unsafe-assignment` rule can help you identify such instances where an ‘Any’ value might be assigned unsafely.

To illustrate with a simple example:

typescript let foo: any = “hello”; let bar: number = foo; // TypeScript will throw an error here if no-unsafe-assignment is enabled.

The second line of code will cause Eslint to emit an error if the `no-unsafe-assignment` rule is enabled because an ‘Any’ value is being assigned to a ‘number’ type.

As [Doug Crockford](https://www.brainyquote.com/authors/doug-crockford-quotes), creator of JSON and a profound voice in the tech space, once stated, “The good thing about reinventing the wheel is that you can get a round one”. This quote reinforces our understanding about maintaining safety and code quality by limiting the unsafe use of ‘Any’ values.

Understanding the Concept of Typescript-Eslint No-Unsafe-Assignment

Typescript-Eslint No-Unsafe-Assignment: Unsafe Assignment Of An Any Value

The Typescript-ESLint management tool comprises a set of rules designed to help developers write safer, more effective TypeScript code. Among these rules is the ‘no-unsafe-assignment’ regulation, which focuses on dissuading developers from employing any form of unsafe assignment of an ‘any’ value within their project’s source code.

Conceptualizing ‘no-unsafe-assignment’

‘No-unsafe-assignment’ chiefly alerts developers when they assign values from variables that are assigned as ‘any’ types. This rule aims to discourage programmers from bypassing or ignoring TypeScript’s inherent type-safety benefits and mandates. By disabling or dismantling TypeScript’s type-checking features, developers risk running into issues during runtime, impacting error detection and debugging efficiency.

An Illustrative Example

In the above example,

has no explicit type defined, rendering it an ‘any’ type in TypeScript’s eyes. Upon assigning its value to

(whose type has explicitly been declared as ‘string’), an error would be thrown by the ESLint engine due to violation of the ‘no-unsafe-assignment’ rule.

Resolving ‘no-unsafe-assignment’

To address this problem, you must consider providing concrete type definition instead of using the ‘any’ type. In TypeScript, applying specific types strengthens the potent static typing architecture, enabling developers to catch errors efficiently at compile-time rather than at runtime.

Email Etiquette Rules

For instance, instead of assigning the ‘any’ type, an explicit type assignment can effectively manage this:

The ‘no-unsafe-assignment’ rule encourages developers to leverage TypeScript’s full potential and work with the certainty of type safety. By doing so, developers create a more robust, reliable, and efficient application, enhancing both user experience and code maintainability. As Nick Scialli once stated, “TypeScript is not about guaranteeing that your code is free of bugs; it’s about catching the most common mistakes with less effort and time.”

Decoding the Errors: “Unsafe Assignment Of An Any Value”

Typescript-Eslint No-Unsafe-Assignment: Unsafe Assignment Of An Any Value

TypeScript-Eslint’s rule `no-unsafe-assignment` vigilantly warns developers when this sort of scenario occurs. The purpose behind it is to help enforce TypeSafety, a principle aspect that makes TypeScript standout as compared to JavaScript.

Understandably, the very essence of using TypeScript is to leverage static typing for catching errors during compile time, rather than runtime like in JavaScript. By applying loose `any` values without constraint, unintentionally, one may drift against the benefits provided by TypeScript, potentially leading to troublesome bugs that are harder to track.

Let’s delve into a brief example:

Consider we have a function that accepts a parameter of type `any` and assigns its value to another variable of known type.

In this instance, TypeScript-Eslint will display an `Unsafe assignment of an any value`warning. This is because `value` is not guaranteed to always be a number, yet it’s assigned to `numberValue` which only expects numerical entries.

One way to mitigate this issue and adhere to TypeScript-Eslint’s `no-unsafe-assignment` rule would be through Type Checks or Type Assertions. Here’s an illustration:

Here, a check is performed before assignment. If the value isn’t a number, there won’t be an assignment, hence preventing `Unsafe Assignment of an Any Value` warning.

In TypeScript’s ecosystem, every precaution taken to ensure TypeSafety bolsters code quality and aids in maintaining a cleaner, bug-free format.

“It’s hard enough to find an error in your code when you’re looking for it; it’s even harder when you’ve assumed your code is error-free.” — Steve McConnell

Online reference: ESLint – no-unsafe-assignment

Practical Strategies to Avoid Unsafe Assignments in TypeScript-Eslint

Typescript-Eslint No-Unsafe-Assignment: Unsafe Assignment Of An Any Value

Let’s understand the concept first: TypeScript employs type safety as one of its core strengths. When assigning variables or properties, each follows explicit or inferred types. Nevertheless, TypeScript provides an escape hatch – the `any` type that can potentially bring the entire type system to its knees. The `any` value bypasses type-checking completely, making it susceptible to throwing unpredictable runtime errors.

Now, how do we avoid unsafe assignments? Below we provide some feasible strategies:

1. Preferential use of unknown over any: In scenarios where you’re uncertain about a variable’s type, it is recommended to utilize the ‘unknown’ type rather than ‘any’. This forces you to carry out necessary type checking before manipulating the variable.

Contrast the following examples to illustrate this: code let a: any = “I could be anything”; a.trim(); // This will compile but might fail at runtime

let b: unknown = “I could be anything”; b.trim(); // This won’t compile because TypeScript doesn’t know if b has a .trim() method

2. Type inference and declaration: TypeScript features robust capabilities for type inference which minimize the necessity for direct type definitions. Leverage them whenever possible. 3. Usage of Type Guard Functions: These are functions that perform type checking. TypeScript recognizes their return type as a type predicate.

Lastly, while restructuring your project to entirely eliminate the usage of `any` could be taxing and possibly extraneous, introducing incremental checks could be a viable alternative. Start by enabling typescript-eslint/no-unsafe-assignment rule in your eslint config file, and over time, pay down the debt of `any` usage whenever working on parts of the system. Being intentional in enabling type guards and leveraging type inference would go a long way.

As Amiad Hadad said: “In a large code base with many developers involved, using ‘any’ can be disastrous. It’s like shooting in the dark, disregarding TypeScript’s superpowers.”

That’s where TypeScript-eslint No-Unsafe-Assignment rule comes into play – a vanguard in maintaining your system’s safety and performance.

How TypeScript’s Strict Typing Standards Impact Eslint No-Unsafe-Assignment

Typescript-Eslint No-Unsafe-Assignment: Unsafe Assignment Of An Any Value

The Intersection of TypeScript and Eslint No-Unsafe-Assignment

In simple terms, Eslint’s rule of ‘no-unsafe-assignment’ disallows the assignment of values with more permissive types (any) to variables with less permissive or specific types. This rule checks for unsafe assignments of values with any type to variables, properties, and array elements. How TypeScript plays a significant role here ties back to its foundational insistence on maintaining strong, non-inferior type safety.

Selecting –strictTrue as part our TypeScript configuration helps us proactively prevent common JavaScript errors during code writing phase itself. Particularly, in cases of an “any” assignment, this flag along with no-unsafe-assignment in ESLint ensures that developers are consciously making ‘any’ type decisions rather than accidentally creating less maintainable and harder-to-debug code.

Code Example:

Given the following TypeScript code snippet:

This code would be flagged by Eslint’s no-unsafe-assignment rule. The user variable is of ‘any’ type and its assignment to myUser, which is of a more specific User interface type, goes contrary to strict type safety.

The Value of Strict Type Safety

Elaborating on the significance of strict type safety, eminent developer Robert C. Martin, articulately encapsulated it in the following way:

“Our inability to handle complexity is the main source of defects. TypeScript and strong static typing help us manage this complexity.”

Such precise management of code complexity is crucial for large scale projects where even small bugs or inconsistencies can scale into significant problems.

Key Takeaway

In essence, the intersection of TypeScript’s rigid typing provisions with Eslint’s no-unsafe-assignment rule works to enhance code quality, readability, and maintainability by ensuring that type assignments adhere strictly to the defined rules.

<p>The issue encapsulated by Typescript-Eslint: No-Unsafe-Assignment, importantly incorporates unsafe assignment of an ‘any’ value. This rule principally disallows the conduct of assigning variables of type ‘any’. Indisputably it’s an integrated linting tool specifically for TypeScript which strengthens code quality through automating the identification and eradication of antipatterns or potential areas of concern. Moreover, its role within programming contexts can be instrumental in minimizing potential coding defects and enhancing efficiency.</p>

<p> Comprehending how to leverage the Typescript-Eslint: No-Unsafe-Assignment feature entails a grasp of TypeScript semantics. The ‘any’ type in TypeScript is potentially hazardous as it subverts the benefits that static typing brings – like early-error checking and autocompletion – essentially transforming portions of your code into dynamically-typed language. </p>

<table border=”1″> <tr> <td><code>let someVariable: any = 5;</code></td> </tr> <tr> <td><code>let someOtherVariable: number = someVariable;// No error when assigning</code></td> </tr> </table>

<p>In this case, if `someVariable` isn’t in actuality a number, we’ve unwittingly introduced a bug in `someOtherVariable`. Avoiding using any and configuring no-unsafe-assignment helps us maintain sanity checks in our codes.</p>

<p>As Brian Kernighan, one of the creators of C programming language quoted “Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.”</p>

<p>There’s no arguing that Typescript-Eslint No-Unsafe-Assignment provides a valuable safety net for developers, particularly relating to type-checking discipline, enabling you to write safer and more maintainable code.</p>

  • Ts2339: Property Tsreducer Does Not Exist On Type Defaultrootstate
  • Cannot Find Module React-Dom Client From Node Modules Testing-Library React Dist Pure Js

typescript unsafe assignment

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 You must be signed in to change notification settings

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] fails to infer the type from class properties #2109

@photonstorm

photonstorm commented May 26, 2020

{ IEventInstance } from './IEventInstance'; export class EventEmitter { events: Map<string, Set<IEventInstance>>; constructor () { this.events = new Map(); } }

The rule is flagging the creation of the Map in the constructor as being unsafe, claiming it can accept types, even though the type is enforced by the property in the class.

I see no logical reason why this should be considered an unsafe assignment when the type is clearly enforced by the property. TypeScript itself prevents incorrect insertion of values into this Map.

In order to stop the rule complaining, the following works:

{ IEventInstance } from './IEventInstance'; export class EventEmitter { events: Map<string, Set<IEventInstance>>; constructor () { this.events = new Map<string, Set<IEventInstance>>(); } }

However, this is just duplicating the type already defined.

version

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

  • 👍 3 reactions

@photonstorm

bradzacher commented May 26, 2020

Yeah I ran into this when attempting to introduce the rule into this codebase.

For some reason TS doesn't automatically infer the type of the RHS if it's .
This works 100% of the time for , so it's unique to map.

I it's due to how the constructor is defined.

MapConstructor { new(): Map<any, any>; new<K, V>(entries?: readonly (readonly [K, V])[] | null): Map<K, V>; readonly prototype: Map<any, any>; } declare var Map: MapConstructor;

Compared to :

SetConstructor { new <T = any>(values?: readonly T[] | null): Set<T>; readonly prototype: Set<any>; } declare var Set: SetConstructor;

Note that has an empty constructor which defaults to s, and a parameterised constructor that doesn't.
OTOH only has a parameterised constructor, but its generic type has a default.

Unsure if it's a "bug" in TS or not. Either way, it's something that will have to be special cased in the rule unfortunately.

Sorry, something went wrong.

@bradzacher

Doing some research, it looks like this is intentional.
Clicking through the , you find which did !

However because has multiple type parameters, this caused weirdness with extending ( ), which then lead to just the change to just the constructor being reverted ( ).

So the map constructor being like this is completely intentional, which means we'll have to add a special case for .

Thanks for the quick update. Sounds like this is quite the rabbit hole! I've sadly found I have had to disable all of the rules for my codebase because they seem to conflict with TS in subtle ways. I don't envy you having to work with such a moving feast as this! Will keep an eye out at the Change Log.

  • 👍 1 reaction

bradzacher commented May 27, 2020

How so? If there are problems with the rule, please report them so we can look into getting them fixed!

@Raynos

Raynos commented Jun 1, 2020

I ran into this issues today as well.

Would be lovely if can be special cased in because it's builtin into typescript stdlib definitions.

If I implement my own custom Generic and have an signature in my own class definition then it's a "bug" in my constructor because I shouldn't use .

Fixing TypeScript standard library for ES6 / etc to remove is a large task ... so special casing in would be very practical.

@Raynos

Here's an example workaround for JSDoc.

Foo { constructor () { // https://github.com/typescript-eslint/typescript-eslint/issues/1943 /* eslint-disable @typescript-eslint/no-unsafe-assignment */ /** @type {Map<string, FunctionConfiguration[]>} */ this._profiles = /** @type {Map<string, FunctionConfiguration[]>} */ (new Map()) /* eslint-enable @typescript-eslint/no-unsafe-assignment */ } }

JSdoc does not support but does support casts ... I opened an issue in TypeScript for the lacking JSDoc functionality in function calls ( ).

@github-actions

Successfully merging a pull request may close this issue.

@photonstorm

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Unsafe assignment of an `any` value when using in to confirm object property in unknown

I am trying to write some code to handle errors in a JSON:API response.

I'm confused because @typescript-eslint gives an error for the line const { detail } = data.errors[0]; :

Unsafe assignment of an any value.

So I tried this:

This also gives an error:

Unsafe member access .detail on an any value.

The docs on no-unsafe-assignment suggest typing the object. But in my case, I'm trying to work with unknown to be extra safe so that my runtime code is not reliant on types to process the response. I thought by using property in object and typeof object.property === type I could get eslint to understand that the type is not any , but this isn't working.

What am I doing wrong?

  • typescript-eslint

Patrick Kenny's user avatar

The error comes from the linter; the any assignment is valid.

Typescript infers that the entire data.errors as any[] from the Array.isArray(data.errors) check. This inference does not change after the subsequent check that looks for the 'detail' prop of data.errors[0] . This inference is a Typescript feature .

To prevent the errors thrown by the linter, you'll need to override the isArray method's interface:

This will change the type of data.errors to readonly unknown[] | unknown[] .

gnerkus's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged typescript eslint typescript-eslint or ask your own question .

  • Featured on Meta
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Announcing a change to the data-dump process
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • What is a proper word for (almost) identical products?
  • Rambam’s ancient writing spilled on by coffee
  • Are hot air balloons regulated by ATC or can they fly without reporting to ATC?
  • How could breastfeeding/suckling work for a beaked animal?
  • Fantasy book(s) with magic powers gained from rose gold rings
  • Can a character forego one of their attacks if they have only one?
  • Requesting explanation on the meaning of the word 'Passerby'?
  • How should I understand "mit" in this sentence?
  • Olive tree suckers but no top growth at all
  • Does Przeworski et al.'s alternation rule imply the U.S. during Roosevelt administration shall be categorized as dictatorship?
  • Clock that is twice as fast
  • Is a continuous function a generalization of an adjunction?
  • Had there ever been a plane crash caused by flying too high and exploding?
  • Validity of AIC When Comparing Models with Varying Dispersion Parameters
  • Regarding banishment and force cage
  • In the onion-like elemental layers of a large mature star the neon is closer to the surface than oxygen, even though it is more massive... Why?
  • Does a rocket moving in a circle expel exhaust at a greater velocity?
  • Can a non-symmetrical distribution have the same areas under the PDF in the two sides around the mean?
  • I want to number two formula in equation, aligned and split environment
  • An arrangement of hyperplanes
  • Why does the pet's water bowl overflow?
  • Can Curve25519 shared secret be safely truncated to half its size?
  • Which distribution should I choose when my interest is the the interaction term (the poisson or negative binomial)?
  • Can a bad paper title hurt you? Can a good one help you?

typescript unsafe assignment

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

IMAGES

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

    typescript unsafe assignment

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

    typescript unsafe assignment

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

    typescript unsafe assignment

  4. Typescript. Unsafe assignment of an `any` value. Animated

    typescript unsafe assignment

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

    typescript unsafe assignment

  6. typescript

    typescript unsafe assignment

VIDEO

  1. Assignment Operators in Typescript

  2. Typescript series: PART 7 ASSIGNMENT OPERATORS. Governor house typescript exam preparation

  3. Assignment school toilets are unsafe advertisment

  4. Typescript 45 Questions Assignment Part 20

  5. How I Deal With Unsafe Packages

  6. Typescript Assignment Governor House IT Course 13

COMMENTS

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

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

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

    Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company Visit the blog

  5. Making TypeScript Truly "Strongly Typed"

    TypeScript provides the "Any" type for situations where the shape of data is not known in advance. However, excessive use of this type can lead to problems with type safety, code quality, and developer experience. ... The no-unsafe-assignment rule searches for variable assignments in which a value has the any type. Such assignments can mislead ...

  6. Overview

    @typescript-eslint/ no-unsafe-argumentDisallow calling a function with a value with type any: : 💭: @typescript-eslint/ no-unsafe-assignmentDisallow assigning a value with type any to variables and properties: : 💭: @typescript-eslint/ no-unsafe-callDisallow calling a value with type any: : 💭: @typescript-eslint/ no-unsafe-declaration ...

  7. 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 […]

  8. Safely Assigning Any Values in TypeScript

    Unsafe Assignment of an Any Value. In JavaScript, the `any` type is a catch-all type that can be assigned to any other type. This can be useful for working with unknown or unexpected values, but it can also lead to errors if you're not careful. ... In TypeScript, any values are denoted by the keyword `any`. Any values are often used as a ...

  9. Avoid assigning a value with type any

    rulesets: - typescript-best-practices # Rules to enforce TypeScript best practices. Create a static-analysis.datadog.yml with the content above at the root of your repository Use our free IDE Plugins or add Code Analysis scans to your CI pipelines

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

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

    TypeScript is a language for application-scale JavaScript development. TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. Members Online

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

  14. Typescript-Eslint No-Unsafe-Assignment: Unsafe Assignment Of An Any

    The TypeScript-Eslint No-Unsafe-Assignment rule plays a crucial role in adaptive programming. It helps mitigate the risk of unsafe code execution by restricting the assignment of `any` values. Primarily, it aims to protect the structural integrity and functional efficiency of your application by facilitating safer assignments.

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

  16. [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.

  17. 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]?:

  18. typescript

    The docs on no-unsafe-assignment suggest typing the object. But in my case, I'm trying to work with unknown to be extra safe so that my runtime code is not reliant on types to process the response. I thought by using property in object and typeof object.property === type I could get eslint to understand that the type is not any , but this isn't ...

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