How come ESLint isn't raising any issues about the implicit `any` return value from the function call?

Why is ESLint not flagging the implicit any on this specific line:

// The variable `serializedResult` is of type `any`, which is permissible because the return value 
// of `sendMessage(...)` is a `Promise<any>`. But why doesn't ESLint throw an error?
const serializedResult = await browser.runtime.sendMessage(serializedPacket);

Configuration files:

// Type declarations for functions are pulled from `index.d.ts`:
declare namespace browser.runtime
{
    ...
    function sendMessage(message: any, options?: _SendMessageOptions): Promise<any>;
    function sendMessage(extensionId: string, message: any, options?: _SendMessageOptions): Promise<any>;
    ...
}
// Configuration in .eslintrc.json
{
    "env": 
    {
        "browser": true,
        "es2021": true
    },
    "extends": 
    [
        "eslint:recommended",
        "plugin:@typescript-eslint/recommended"
    ],
    "parser": "@typescript-eslint/parser",
    "parserOptions": 
    {
        "ecmaVersion": "latest",
        "sourceType": "module"
    },
    "ignorePatterns": 
    [
        "bin/**"
    ],
    "plugins": 
    [
        "@typescript-eslint"
    ],
    "rules": 
    {
        "prefer-rest-params": "off",
        "@typescript-eslint/no-explicit-any": "error"
    }
}

// Content of tsconfig.json:
{
    "compilerOptions":
    {
        "target": "es2022",
        "module": "NodeNext",
        "moduleResolution": "NodeNext",
        
        "strict": true,
        "noImplicitAny": true,
        "esModuleInterop": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true,
        "sourceMap": true
    }
}

Could I be overlooking something? Is this setup correct?

Answer №1

In this scenario, we have the utilization of two essential tools:

  • ESLint (known as a linter): It operates by executing a customizable list of rules, with each rule focusing on identifying specific issues within the codebase.
  • TypeScript (referred to as a language): This tool allows developers to write code using JavaScript syntax along with additional constructs for defining types. TypeScript includes a type checker that highlights any inconsistencies in data types throughout the code.

The noImplicitAny compiler option within TypeScript specifically flags cases where the type of certain parameters or variables cannot be automatically inferred. However, it does not address instances where values are deliberately set to type any.

To effectively pinpoint areas in the code where any is used, developers can rely on various lint rules provided by typescript-eslint, which incorporates TypeScript-specific functionalities into ESLint:

  • plugin:@typescript-eslint/no-unsafe-assignment
  • plugin:@typescript-eslint/no-unsafe-return
  • ...and more detailed in typescript-eslint.io/rules

These rules necessitate utilizing type information during the linting process to identify any occurrences accurately. By default, ESLint config may not activate these rules unless extended from

"plugin:@typescript-eslint/recommended"
; hence enabling
"plugin:@typescript-eslint/recommended-type-checked"
is crucial. For further insights on preset typescript-eslint configurations, visit typescript-eslint.io/linting/configs.

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

Using Typescript inject with Vue 3 is currently not functioning as expected. The issue arises when trying to create spread types from object types

When using Vue 3 and TypeScript, an error is encountered (as shown below) only when the script lang="ts" attribute is present. Can someone provide insight into why the inject function in Vue 3 with TypeScript does not function correctly? ERROR in src/compo ...

Modifying the date format of the ag-Grid date filter

On my Angular 5.2.11 application, I utilize ag-grid to showcase a table. The date column is configured with the default date filter agDateColumnFilter as per the documentation. After enabling browserDatePicker: true, the Datepicker displays dates in the ...

The conversion of an array to Ljava/lang/Object is not possible

I'm currently working on a project using NativeScript app with TypeScript where I am trying to pass an array of android.net.Uri to a function. However, when attempting to do so, I encounter an error mentioning that the 'create' property does ...

Mocking the Date object accurately in a test using the toHaveBeenCalledWith method in Jest

I'm currently working on unit testing a service that generates a cookie based on an API response I developed. export interface ISessionService { createSession(): Observable<ApplicationSession>; validateSession(): Observable<boolean> ...

The module 'module://graphql/language/parser.js' could not be resolved

I'm facing an issue while creating a React Native TypeScript project on Snack Expo. Even though I have added graphql to the package.json and included the types file, I keep getting this error : Device: (1:8434) Unable to resolve module 'module:/ ...

What event type should be used for handling checkbox input events in Angular?

What is the appropriate type for the event parameter? I've tried using InputEvent and HTMLInputElement, but neither seems to be working. changed(event) { //<---- event?? console.log({ checked: event.target.checked }); } Here's the com ...

How can I prevent the 'eslint(react-hooks/exhaustive-deps)' error from occurring on a custom React Hook that uses useCallback?

Here is a custom React Hook designed to work with the IntersectionObserver: import { useCallback, useRef, useState } from 'react'; type IntersectionObserverResult = [(node: Element | null) => void, IntersectionObserverEntry?]; function useIn ...

The compatibility issue between Angular's ngModel and Value in input components

Encountering a challenge with the angular form. My objective is to create a form pre-filled with default values that can be edited. Upon validation, the form should submit the data to the MySQL database. Below is the component.html code: <form #adopt=& ...

Leveraging TypeScript alongside body-parser to access properties within req.body

I'm currently developing a web application using TypeScript and integrating the body-parser middleware to handle JSON request bodies. I've encountered type errors while attempting to access properties on the Request.body object. For instance, wh ...

Exporting a module from a TypeScript definition file allows for seamless sharing

I am in the process of developing a definition file for the Vogels library, which serves as a wrapper for the AWS SDK and includes a property that exports the entire AWS SDK. declare module "vogels" { import AWS = require('aws-sdk'); export ...

Unveiling the proper extension of component props to default HTML button props

Currently, I am in the process of developing a button component that includes a variant prop to specify its color scheme. Below is a simplified version of the code: interface Props extends React.HTMLProps<HTMLButtonElement> { variant: 'yellow ...

The use of refs on Function components in SVG is not supported. Any attempts to access the ref will result in an

I am currently working on integrating a navigation bar component using an SVG image in Next.js. While attempting to import and utilize the SVG image, I encountered an error that I couldn't resolve. I tried using Emotion JS to create and use the SVG, ...

What is the proper way to incorporate ts-nameof in the gulp build process and encounter the error message: 'getCustomTransformers' is a compiler option that is not recognized

Utilizing ts-nameof in my TypeScript files, similar to this example in a .ts file: import 'ts-nameof'; export class MyTsNameOfTest { public testTsNameOf() { const nameString = nameof(console.log); } } My Gulp build task setup - followi ...

Developing a TypeScript library through modular class implementation

I have developed a Web API and now I want to streamline my code by creating a library that can be reused in any new project I create that interacts with this API. My goal is to organize my code efficiently, so I plan to have separate classes for each endp ...

Exploring the world of logging in Nestjs to capture response data objects

I'm eager to implement logging for incoming requests and outgoing responses in NestJs. I gathered insights from various sources including a post on StackOverflow and a document on NestJs Aspect Interception. I'd love to achieve this without rely ...

Testing NextJS App Router API routes with Jest: A comprehensive guide

Looking to test a basic API route: File ./src/app/api/name import { NextResponse } from 'next/server'; export async function GET() { const name = process.env.NAME; return NextResponse.json({ name, }); } Attempting to test ...

Exploring the Relationship Between the ngOnInit and ionViewWillLoad Lifecycle Hooks

After a few months of utilizing Ionic Framework (ionic-angular 3.9.2 latest) for developing Progressive Web Apps, I find myself pondering the distinction between ngOnInit and ionViewWillLoad. If my understanding serves me right, ngOnInit is an Angular lif ...

How can one access DOM elements (getting and setting values) that are nested within an *ngFor loop?

How can I access the <span> and <select> elements in my code template shown below? <div *ngFor="---"> <div> <span></span> <select> <option></option> <option></option> ...

Is Angular Template Polymorphism Failing?

So I'm working with a base class that has another class extending it. export class Person { public name: string; public age: number; } export class Teacher extends Person { public yearsTeaching: number; } Now, in my component, I need to ...

Ways to ensure that text wraps to a new line when it exceeds the container's width

I am currently working on implementing a line of text within an ion-card element, but the challenge lies in the fact that the length of the text varies each time. In order to ensure that the entire text is visible and not cut off, especially on devices wit ...