TS7017: utilizing implicit any type for type inference

Below is the shortened code snippet causing an error:

export default function formatSql(this: EscapeFunctions, sqlQuery: string, values: QueryParams) {

    if (isPlainObject(values)) {
        console.log(values[p]); // <-- Element implicitly has an 'any' type because type 'QueryParams' has no index signature.
    } else if (Array.isArray(values)) {
        // ...
    } else {
        throw new Error(`Unsupported values type`);
    }
    // ...
}

QueryParams is defined as:

export type QueryParams = StringMap | any[];
export interface StringMap {
    [_:string]: any,
}

Therefore, StringMap has an "index signature" according to the definition, and isPlainObject is defined as:

export function isPlainObject(obj: any): obj is object  {
    return isObject(obj) && (
        obj.constructor === Object  // obj = {}
        || obj.constructor === undefined // obj = Object.create(null)
    );
}

Despite setting isPlainObject to return obj is StringMap, Typescript still raises an issue.

Why is this happening? Is there a solution to avoid typecasting all elements?

Answer №1

Essentially, an Array still adheres to the type {[key: string]: any}. This can be confirmed by executing const test: StringMap = [];. The TypeScript compiler will not raise any issues. Therefore, it is essential to eliminate the possibility that values is an array before proceeding.

Furthermore, the return type of your isPlainObject function is currently defined as obj is object, which is too broad. This causes the code to overlook the object's index signature. It should be revised to obj is StringMap.

As a practical solution, two steps should be taken:

  1. Check if the value is an array in the initial if statement
  2. Update the return type declaration of isPlainObject to obj is StringMap

In essence, the revised implementation would resemble the following:

export function isPlainObject(obj: any): obj is StringMap {
  // ...
}

export default function formatSql(values: QueryParams) {
  if (Array.isArray(values)) {
    // ...
  } else if (isPlainObject(values)) {
    console.log(values[p]);
  } else {
    throw new Error(`Unsupported values type`);
  }
}

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

What is the best way to transition this endpoint from JavaScript to TypeScript?

I'm in the process of building a chat application with the t3 stack. I've successfully created a socket endpoint using JavaScript, but now I'm facing some challenges as I try to convert it to TypeScript. import { Server } from "Socket.I ...

Cannot proceed with module import: Type 'ModuleWithProviders<T>' must have a single type argument

ERROR in node_modules/@angular/fire/firestore/firestore.module.d.ts:7:74 - error TS2314: Generic type 'ModuleWithProviders<T>' requires 1 type argument(s). 7 static enablePersistence(persistenceSettings?: PersistenceSettings): ...

Leveraging GetServerSideProps for Dynamic URL Query Parameters

While working on querying the parameter in the URL within getServerSideProps, I encountered an error where ID was undefined in the DetailThemepage function. My Next.js version is V.13 and the directory structure is app/detail/[id]/page.tsx. http://loca ...

Tally up identical words without considering differences in capitalization or extra spaces

Let's take an example with different variations of the word "themselves" like "themselves", "Themselves", or " THEMSelveS " (notice the leading and trailing spaces), all should be considered as one count for themselves: 3 ...

Using both Typescript and Javascript, half of the Angular2 application is built

My current project is a large JavaScript application with the majority of code written in vanilla JavaScript for a specific platform at my workplace. I am looking to convert this into a web application that can be accessed through a browser. I believe thi ...

How to transform a file into a uInt8Array using Angular

Looking to implement a feature where I can easily upload files from Angular to PostgreSQL using a Golang API. In my Angular component, I need to convert my file into a uInt8Array. I have managed to convert the array, but it seems to be encapsulated in som ...

This object does not have support for the attribute or method "getAttribute"

I've searched for solutions, but nothing seems to work for me and now I'm feeling quite lost. My current setup involves Cordova, Ionic, and Angular 2. Below is the HTML snippet: <ion-col *ngFor="let value of myButtonsFirstRow" width-25> ...

TypeScript making erroneous assumptions about property values post-setting

My TypeScript object has a boolean property that causes some confusion. When I update the object's value to false, TypeScript seems to believe it will remain false indefinitely (at least within the scope), even though it can be modified: const obj = { ...

Tips for choosing and filtering the preferred object in ES6

Consider this array structure: const testData = [ { group: "Team1", info: [ { key: 123, person: "Alice", type: "Football" }, { key: 456, person: "Bob", type: " ...

Save JSON Tree data in the Database

Given a tree structure JSON, I am tasked with creating an API to insert all the data into a database at once. The organization entities can have multiple parents and children relationships. An example of the JSON data: { "org_name": "orga ...

React dynamic table

I've been experimenting with creating a dynamic table in React that allows users to add and delete rows. I need the data entered by the user to be saved, possibly using in-state management so that I can work with it later. Essentially, I'm looki ...

Building a customized Mui clip with child support: A step-by-step guide

Looking to create a customized chip that can handle both single and nested declarations? Check out this example using MUI v5. interface StyledModalChipProps { theme: Theme children: React.ReactNode } export const StyledModalChip = styled(Chip)<Styled ...

Assigning variables within Redux saga generators/sagas

Consider this scenario: function* mySaga(){ const x = yield call(getX) } The value of const x is not determined directly by the return value of call(getX()). Instead, it depends on what is passed in mySaga.next(whatever) when it is invoked. One might a ...

Moving a custom folder to production on Vercel with Next.js

I am currently working on developing a project using the NextJS environment. In this project, I have some JSON files stored in a folder within my root directory, and I am reading the content of these files in my code. Everything works fine on my local mach ...

IntelliJ is indicating a typescript error related to react-bootstrap-table-next

Working with react-bootstrap-table-next (also known as react-bootstrap-table2) has been causing a Typescript error in my IntelliJ environment, specifically on the validator field within my column definition. Despite trying various solutions, such as adding ...

Creating a Node.js asynchronous setup function

I'm in the process of transitioning from Nodejs v12 to v14 and I've noticed that v14 no longer waits for the setup function to resolve. My setup involves Nodejs combined with Express. Here's a simplified version of my code: setup().then(cont ...

Using Typescript, the type T or a function that returns T can be utilized in various scenarios

You can check out a demonstration on this interactive platform. In creating a simple generic type that represents either a variable or a function returning a variable, there was an issue with the typical typeof arg === 'function' check. The erro ...

Is there a way for me to implement a service method that retrieves the onSnapshot result, allowing me to seamlessly integrate it into my Component or Ionic Page?

Currently, I am using "ionic-angular": "3.7.1" along with Firebase Cloud Firestore. My goal is to retrieve all the documents from the Post collection whenever they are updated, deleted, or added. I have been informed that by calling the onSnapshot Method, ...

Visual Studio Code is encountering issues when trying to start a Node application

I am in the process of setting up a workflow for an express app using TypeScript, Visual Studio Code, and gulp. Here is the structure of my project: src/ <-- source files Start.ts Server.ts models/ Contact.ts Organization.ts bin/ <- ...

Guide on loading a PDF asset dynamically within an Angular application with the help of webpack

I am having trouble loading a PDF file into my Angular app, which is running on the webpack dev server. I am using the HTML <object> tag with the data attribute to achieve this. The issue arises because the PDF path is generated dynamically at runti ...