JavaScript - Imported function yields varied outcome from module

I have a utility function in my codebase that helps parse URL query parameters, and it is located within my `utils` package. Here is the code snippet for the function:

export function urlQueryParamParser(params: URLSearchParams) {
  const output:any = {};
  const searchParams = new URLSearchParams(params);

  new Set([...searchParams.keys()])
    .forEach(key => {
      output[key] = searchParams.getAll(key).length > 1 ?
        searchParams.getAll(key) :
        searchParams.get(key)
    });

  return output;
}

To make this function accessible throughout my project, I export it in the main index file along with other modules like so:

export * from './utils/urlQueryParamParser'

When I import and use this function in one of my modules using the statement

import { urlQueryParamParser } from '@mypackages/utils'
, I notice that the result returned is not as expected:

{
    "[object Iterator]": null
}

However, if I directly copy this function into the module where I am calling it, the return result is correct and looks something like this:

{
    "filter": "all",
    "query": "",
    "range": "today",
    "from": "2022-11-22",
    "to": "2022-12-22",
    "claims": [
        "damaged",
        "missing-article"
    ]
}

I am curious about why there is a difference in the results when importing the function versus using it directly within the same file. The TypeScript version used in the module where I import the function is:

"typescript": "^4.7.2",

And the `tsconfig.json` configuration for that module is as follows:

{
  "compilerOptions": {
    // Configuration options here...
  },
  "include": ["src/**/*.ts", "src/**/*.tsx"],
  "files": ["custom.d.ts"]
}

On the other hand, the TypeScript version specified in the package module is:

"typescript": "^4.7.4"

And its corresponding `tsconfig.json` content is provided below:

{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    // Configuration options here...
  },
  "exclude": ["**/node_modules", "**/.*/", "dist", "build"],
  "include": ["src/**/*.ts", "src/**/*.tsx"]
}

Answer №1

Expanding on my previous comment.

My suspicion is that the issue stems from not properly spreading the keys in your array within the file located in the package. Instead of adding each key individually, it seems like you inserted the iterator object as the only element in the array.

It appears that you may have mistakenly used new Set([searchParams.keys()]) instead of

new Set([...searchParams.keys()])
in either your current or past version, leading to a compilation error (potentially due to incorrect caching).

Curiously, TypeScript did not seem to issue a warning when this mistake was made. To avoid similar oversights, I found it necessary to include // @ts-nocheck in my code while trying to replicate the problem.


The challenge lies in reproducing the issue given the limited details provided. For future reference, it would be beneficial to create a project showcasing the problem using CodeSandbox.

Answer №2

If you are working with TypeScript versions older than 2.3.1, you may encounter issues with URLSearchParams not being recognized as an iterable object. This can result in unexpected behavior when trying to spread it, as JavaScript may return "[object Iterator]" instead of raising an error.

It is important to note that the parameter params should be a string or URL['search'], depending on the context of your function. Whether you pass the parameters as a string or the output of another URLSearchParams instance, the outcome will be the same.

The inconsistency in functionality between different cases could be due to mismatched versions in your tsconfig.json and package.json files. It is also possible that packages like @mypackages are using a different version of TypeScript compared to the project utilizing the function. Providing detailed information about your versions and environment would aid in resolving any issues.

Answer №3

I'm taking a shot in the dark here, but have you tried replacing the spread operator with Array.from to see if it works?

function urlQueryParamParser(params: URLSearchParams) {
  const output:any = {};
  const searchParams = new URLSearchParams(params);

  new Set(Array.from(searchParams.keys()))
    .forEach(key => {
      output[key] = searchParams.getAll(key).length > 1 ?
        searchParams.getAll(key) :
        searchParams.get(key)
    });

  return output;
}

Answer №4

Ensure that in the tsconfig.json file of your module, you have correctly set the noEmit flag to true. This is crucial for successful compilation.

Answer №5

One workaround is to utilize the relative path for importing.

import { urlQueryParamParser } from '../mypackages/utils'; // instead of '@packages/utils'

You can also make modifications to the utils/index.js file as follows:

import { urlQueryParamParser } from "./urlQueryParamParser";

export default {
  urlQueryParamParser
};

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

Running a Python script through a Javascript event

I'm looking to enhance my webpage by implementing a feature where users can generate a personalized QR code with the click of a button. My current setup involves a Python script that creates the QR code image and saves it as a .png file. I want to int ...

What is the best way to ensure that circles only touch each other by their edges?

Trying to align three circles touching each other has been a challenge for me. Although I have successfully managed to make two touch, the third one remains elusive. How can I ensure that all three circles are in contact with each other, especially when th ...

Redirecting files from the file system to the emulator is not functioning properly

I am new to Phonegap and need help resolving this issue. In my application, I need to redirect to the List.html file when a button is clicked. Here is the code I have written: button1 function test() { window.location="/home/swift-03/phonegapexa ...

What is the best way to incorporate a JavaScript function into an Angular 2 template?

I need a slider for my project and I am using AdminLTE <input type="text" value="" class="slider form-control" data-slider-min="-200" data-slider-max="200" data-slider-step="5" data-slider-orientation="horizontal" data-slider-sele ...

An issue has arisen when trying to fetch and parse data using React and JavaScript

I am currently facing some challenges with fetching data from an API and displaying it using React. I have encountered errors and I am struggling with parsing the JSON response from the API. I believe that converting the response into an array may help res ...

Is there a way to adjust this callback function in order to make it return a promise instead?

This script is designed to continuously attempt loading an image until it is successful: function loadImage (url = '', callback = () => {}) { utils.loadImage(url, () => { callback() }, () => { loadImage(url, callback) }) } ...

Achieve automated zooming out using highcharts-ng through code

Currently, I am using Highcharts-ng as seen on https://github.com/pablojim/highcharts-ng Upon inspecting the source code, I have noticed some interesting functionalities in the directive utilizing scope.$on which I can leverage for broadcasting. One examp ...

Retrieve progress with easing using jQuery's animate() function

At the moment, I'm utilizing this code to create an animation for a bar-graph-inspired element: $('.anim').animate({ right: `${100-(e/max*100)}%`, backgroundColor: colors[0] },{ duration: 1500, easing: 'easeInQuart&apos ...

The ngOnChanges method fails to exhibit the anticipated modifications in a variable

Trying to grasp the concept of the ngOnChanges() callback, I created an example below. Despite having values for the attributes title and content in the Post interface during compile time, I do not see any logs from ngOnChanges. Please advise on the corre ...

Perform multiple function invocations on a single variable using JavaScript

Is there a way to execute multiple functions on a single object in JavaScript? Maybe something like this: element .setHtml('test'), .setColor('green'); Instead of: element.setHtml('test'); element.setColor('gre ...

The differences between using the opacity attribute in HTML and the opacity property

There are two distinct methods for adjusting opacity in HTML: <div opacity="0.5"></div> and <div style="opacity: 0.5;"></div> I am familiar with setting these values in JavaScript as well: div.setAttribute("opacity", 0.5); and ...

Tips on preventing duplication of APIs when retrieving data using nextjs

In my code, I have a function that can be called either from server-side rendering or client side: export const getData = async (): Promise<any> => { const response = await fetch(`/data`, { method: 'GET', headers: CONTENT_TYPE_ ...

Encountering a problem during the installation of angular-route.d.ts

When trying to install angular-route using the command typings install angular-route --save -global, I encountered an error. Can someone help me resolve this issue? typings ERR! message Unable to find "angular-route" ("npm") in the registry. typings ERR! ...

$.ajax causing a JSON input string malfunction

My web API requires the following JSON format for input: [{ "atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe", "atrSpaClassLegendId": "00D18EECC47E7DF44200011302", "atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"}, { "atrSpaUserId": "47 ...

Looking to change the input field names by increasing or decreasing when clicking on a div using jQuery?

As a beginner in the world of jQuery, I am working on mastering some basic concepts. Currently, my goal is to create auto incrementing/decrementing input field names within a 'div' when clicking on an add/remove button. Below is the HTML code I a ...

What is the best way to utilize namespaces across multiple files in your program

I am currently working with TypeScript 1.6.2 and atom-typescript. In my project, I'm attempting to utilize namespaces across separate files: // Main.ts import * as _ from 'lodash' namespace Test { export var value = true } // Another.ts ...

The ng-click functionality seems to be malfunctioning when used within the controller in conjunction with ng-bind

After coding, I noticed that my ng-click function is not working. When I inspected the element, I couldn't find ng-click displayed anywhere. Can someone please help me figure out what I'm doing wrong? var app = angular.module('myApp' ...

Place a checkbox at the start of each table cell

Is there a way to add a checkbox before the text in the first cell of each row in an HTML table using jQuery? I attempted this method: $("table td:first-child").each(function() { $(this).prepend('<input type="checkbox" class="basic-kpi-row"/&g ...

What are the steps to incorporate @svgr/webpack into turbopack within a next.js project?

I'm encountering an issue with turbopack and @svgr/webpack in my project. According to the documentation, they should work together but it's not cooperating. When I run the project without using --turbo (turbopack), everything functions as expec ...

Show a table with rows that display an array from a JSON object using JavaScript

My current code includes JSON data that I need to display in table rows, but I'm struggling to understand how to do so effectively. The output I am currently seeing is all the rows from the array stacked in one row instead of five separate rows as in ...