0
const sortString = req.query.sort as string
const params = Object.fromEntries(new URLSearchParams(sortString))

Now, when I go to implementation, I get:

declare var URLSearchParams: {
    prototype: URLSearchParams;
    new(init?: string[][] | Record<string, string> | string | URLSearchParams): URLSearchParams;
    toString(): string;
};

Now, I am confused why it's not working on Typescript, because it should accept a string.

How to convert URL parameters to a JavaScript object?

No overload matches this call.
  Overload 1 of 2, '(entries: Iterable<readonly [PropertyKey, any]>): { [k: string]: any; }', gave the following error.
    Argument of type 'URLSearchParams' is not assignable to parameter of type 'Iterable<readonly [PropertyKey, any]>'.
      Property '[Symbol.iterator]' is missing in type 'URLSearchParams' but required in type 'Iterable<readonly [PropertyKey, any]>'.
  Overload 2 of 2, '(entries: Iterable<readonly any[]>): any', gave the following error.
    Argument of type 'URLSearchParams' is not assignable to parameter of type 'Iterable<readonly any[]>'.
      Property '[Symbol.iterator]' is missing in type 'URLSearchParams' but required in type 'Iterable<readonly any[]>'.ts(2769)
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
Sayaman
  • 1,145
  • 4
  • 14
  • 35
  • 1
    [I don't see that error](https://tsplay.dev/Na2l2m); could you make sure your code is a [mre] suitable for pasting into a standalone IDE? If not, could you provide more information about your environment and how it differs from the TS Playground? – jcalz Jun 06 '22 at 19:19
  • 1
    The error is about `entries` which is the argument to `fromEntries`, not about `init`, the argument to `URLSearchParams`, so the title of this question is incorrect. – loganfsmyth Jun 06 '22 at 19:19

1 Answers1

1

The error states that the argument passed to fromEntries must be iterable and is not. Looking at the TS definitions, URLSearchParams is defined as iterable in https://github.com/microsoft/TypeScript/blob/2f13eba42c76d02f2e5c79060d6018ee8c7fecc9/lib/lib.dom.iterable.d.ts#L285, so most likely this definition is not being loaded with whatever TS configuration your project has.

loganfsmyth
  • 156,129
  • 30
  • 331
  • 251