Rule in Eslint for Typescript that enforces explicit typing and prohibits the use of implicit "any

Starting a fresh typescript project with eslint, I'm facing an issue in setting up eslint rules for the tsc command to run smoothly without errors. Specifically, I'm encountering difficulty with the "noImplicitAny" rule defined in tsconfig.json, but I'm unsure how to enforce it using eslint.

.eslintrc.js:

module.exports = {
    extends: [
        "eslint:recommended",
        "plugin:@typescript-eslint/eslint-recommended",
        "plugin:@typescript-eslint/recommended",
    ],
    parser: "@typescript-eslint/parser",
    parserOptions: {
        project: ["tsconfig.json"],
        sourceType: "module",
    },
    rules: {
        "no-undef": "warn",
    },
    plugins: ["@typescript-eslint"],
    settings: {
        "import/resolver": {
            node: {
                extensions: [".js", ".ts"],
            },
        },
    },
};

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "ES6",
    "declaration": true,
    "outDir": "./lib",
    "strict": true,
    "noImplicitAny": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules", "**/__tests__/*"]
}

To summarize, I aim to configure eslint within the .eslintrc.js file to actively identify and warn against any implicit usage of 'any'. How can I adjust the rules to achieve this?

Answer №1

Within TypeScript-ESLint, a set of no-unsafe-* regulations have been enforced:

  • no-unsafe-call - prohibits the invocation of an expression with a type of any
  • no-unsafe-member-access - restricts the usage of any as a member name
  • no-unsafe-argument - disallows passing any as a parameter in a function
  • no-unsafe-assignment - prevents the utilization of any during assignment

Although these rules can be used independently, they are also included in Typescript-ESLint's official recommended-type-checked configuration.

export default tseslint.config(
  eslint.configs.recommended,
  ...tseslint.configs.recommendedTypeChecked,
  ...tseslint.configs.stylisticTypeChecked,
);

For additional configuration options, refer to this page.

In a related context, there is also no-explicit-any. By combining all of these measures, you can effectively shield your codebase against potential any complications.

Answer №2

UPDATE:

After experiencing annoyance with the previous typedef usage due to TypeScript still marking it as a warning even when it implicitly knew the type, I have implemented a new rule:

'@typescript-eslint/no-unsafe-call': 'warn',

This rule warns when a variable is truly of type any based on my observations.

PREVIOUSLY:

ESLint did not allow the addition of a no-implicit-any rule because it overlaps with a TypeScript rule. However, there is a transition rule that should only be used temporarily until you can enable these options in your tsconfig file.

This transition rule enables warnings for implicit parameters or arguments in normal and arrow functions. There are more options available than the ones currently commented out, which are detailed in the linked documentation.

One drawback of this rule is that it flags variables as issues even when TypeScript can infer their types. Since this rule is meant to be temporary until the TypeScript rule can be enabled, I choose to ignore those particular issues.

    '@typescript-eslint/typedef': [
      'warn',
      {
        parameter: true,
        arrowParameter: true,
        // variableDeclaration: true,
        // memberVariableDeclaration: true,
        // objectDestructuring: true,
      },
    ],

Link to GitHub issue regarding no-implicit-any restriction: https://github.com/typescript-eslint/typescript-eslint/issues/3979

Documentation for typedef information can be found here: https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/typedef.md

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for clicking on the center of a leaflet map with protractor

I'm currently facing an issue where I am attempting to click on the center of a map located in the second column of the webpage, which has an offset. However, I am encountering a problem where the cursor always points to the center of the page instead ...

Using ES6 and Typescript, when a button is clicked, apply a class to all TD elements within the button except for the first one. No need for jQuery

A sample table structure is shown below: <table> <tr> <td>1</td> <td>joe</td> <td>brown</td> <td><button onclick="addClasses()">Add Class to add TD's in t ...

order by truthiness

I am working with an array of the following class: export class Tests { id: number; name: string; createdAt: any; succress: boolean; constructor(id: number, name: string, createdAt: any, success: boolean) { this.id = id; this.name = nam ...

Angular 5: Issue with Module Resolution: Unable to locate '@angular/forms/src/validators'

Struggling to develop a unique validator using a directive, but encountering the following error: ERROR in ./src/app/CustomValidators/white-space-validator.directive.ts Module not found: Error: Can't resolve '@angular/forms/src/validators' ...

Enhance Express Middleware with Typescript for advanced functionality

Currently in the process of developing a REST API using Express and Typescript, I am encountering difficulties when trying to extend the Request/Response objects of Express. Although my IDE shows no errors, Typescript throws TS2339 Errors during compilati ...

Searching through all values can be done by following these steps

Need help with implementing a search feature that can search all values in Angular2. Here's the current code snippet: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'filter' }) export class FilterPipe implem ...

Problems with the duration of Shadcn Toasts (Inspired by the react-hot-toast library)

Within a 13.4 Nextjs project (app router), utilizing Typescript and TailwindCSS. I am currently exploring the usage of toasts provided by the remarkable shadcnUI Library, which draws inspiration from react-hot-toast while adding its own unique flair. Imp ...

Implement a delay for a specific function and try again if the delay expires

In my TypeScript code, I am utilizing two fetch calls - one to retrieve an access token and the other to make the actual API call. I am looking to implement a 1-second timeout for the second API call. In the event of a timeout, a retry should be attempted ...

Creating nested return types: A guide to defining function return types within a Typescript class

My large classes contain functions that return complex objects which I am looking to refactor. class BigClass { ... getReferenceInfo(word: string): { isInReferenceList:boolean, referenceLabels:string[] } { ... } } I am considering somethi ...

Transforming JSON into object instances with Angular

I am facing an issue in my Angular application where I need to convert a JSON object into an array. Although the mapping process is successful, the data within the array does not retain the properties and methods of my original object class. This hinders m ...

The Angular7 counterpart of the C# attribute decorator

I'm working with an API method that has an Authorize attribute to verify permissions. [Authorize(ReadIndexes)] public async Task<IActionResult> GetIndexes () { ... } Is there a similar way in Angular to implement permission checks so the API ...

The configuration object is invalid. Webpack has been initialized with a configuration object that does not conform to the API schema

I recently created a basic helloworld react app through an online course, but I encountered the following error: Invalid configuration object. Webpack has been initialized with a configuration object that does not adhere to the API schema. - configur ...

Managing component composition in React/TypeScript: What's the best way to approach it?

I am brand new to the world of typescript, so please be patient with me. My objective is to transform this react component: interface ButtonProps {...} const Button: React.FC<ButtonProps> = ({ children, href, value as = 'button', ...

``There is an issue with Cross-Origin Resource Sharing (CORS) in a Node.js application utilizing TypeScript

I've encountered some issues with my application, specifically regarding CORS. I suspect it may be due to a misconfiguration on my server. The problem arises when I attempt to create a user in my PostgreeSQL database via the frontend. I have a tsx com ...

What is the best way to extract information from a button and populate a form in AngularCLI?

I am currently attempting to enhance my Angular App by using a button to transfer information to a form upon clicking, rather than the traditional radio buttons or select dropdowns. My objective is to incorporate HTML content into the button (such as Mat-I ...

Typescript raises an issue regarding a React component's optional prop potentially being undefined

I have a basic React component that looks like this: interface ComponentProperties { onClick?: () => void; } const CustomComponent = (properties: ComponentProperties) => { if (!properties.onClick) { return <></>; } ...

How come the type checker is not throwing an error for this indexable type?

I recently delved into the Microsoft Typescript Handbook and found myself intrigued by the indexable types chapter. To gain a deeper understanding, I decided to experiment with the code provided. Strangely enough, upon running this particular piece of code ...

The async/await feature in Typescript fails to trigger updates in the AngularJS view

Currently, I am utilizing Typescript 2.1 (developer version) to transpile async/await to ES5. An issue I have encountered is that when I modify any property linked to the view within my async function, the view does not automatically reflect the updated v ...

Tips for maintaining the active state of an item within a component that loops through a dataset

I am working with an array of objects (specifically, posts represented as strings) and I am looking to be able to edit each one individually. However, I am encountering an issue where clicking on the edit button triggers editing for all posts at once: co ...

Ways to obtain the file path of the compiled worker.js loaded from the worker loader, along with its hash

Currently, I am working on a TypeScript React application that utilizes Babel and Webpack for compilation. I have implemented a rule to load my worker with the following configuration: config.module.rules.unshift({ test: /gif\.worker\.js$/, ...