Home > database >  How type URLSearchParams in typescript to receive an object?
How type URLSearchParams in typescript to receive an object?

Time:01-05

I have a function that receive via param an object and this object goes inside the URLSearchParams, after this, I make a toString() and get the answer below:

const object = {
    name: 'Test',
    age: 20
};

function exampleFunction(objectExample) {

   const url = new URLSearchParams(objectExample);
   return url.toString();
};

console.log(exampleFunction(object));
// result: name=Test&age=20

The answer result is what i expected, the problem is when I tried to type this param creating an interface, like:

interface ObjectTest { name: string, age: number }

 function exampleFunction(objectExample: ObjectTest) {
    
       const url = new URLSearchParams(objectExample: ObjectTest) << /* error, URLSearchParams expect a type Record<string, string> */;
       return url.toString();
    };

Whitout typing, the code works fine,my question is: how can I type this params to receive an object if my URLSearchParams expect other thing? I already try pass an object stringfy (like JSON.stringfy(object), but the result is something like // {"ma,e":"Test","age%age"#A@)p= instead of name=Test&age=20 )

CodePudding user response:

URLSearchParams takes an object as an argument, but all the values of the object have to be strings.

Record is a utility type. Record<string, string> is a type given for an object whose keys and values are strings.

So you can convert the age to a string to fix the error:

interface ObjectTest { name: string, age: number }

function exampleFunction(objectExample: ObjectTest) {
    const url = new URLSearchParams({...objectExample, age: objectExample.age.toString()})
    return url.toString();
};

Playground

  •  Tags:  
  • Related