Home > Enterprise >  How to type URLSearchParams in typescript
How to type URLSearchParams in typescript

Time:08-07

I am trying to limit the Record type of params passed to URLSearchParams to a specific amount of strings as shown below:

interface GetCoordsParams {
    params: Record<'city' | 'appid' | 'limit', string>;
};

export const createGetCoordsQuery = async (params: GetCoordsParams) => {
    const query = new URLSearchParams(params).toString();
    await fetch(`http://api.geo.com/1.0/direct?q=${query}`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        },
    });
};

Unfortunately, typescript doesn't let me do that by throwing

Argument of type 'GetCoordsParams' is not assignable to parameter of type 'string | string[][] | Record<string, string> | URLSearchParams | undefined'.

CodePudding user response:

The problem is your interface defines a params property.

So basically it's expecting params.params.

Easiest way to change this is probably just turn it into a type that doesn't have a sub property of 'params'.

type GetCoordsParams = Record<'city' | 'appid' | 'limit', string>


export const createGetCoordsQuery = async (params: GetCoordsParams) => {
    const query = new URLSearchParams(params).toString();
    }

CodePudding user response:

GetCoordsParams defines the data you want on a property named params.

So you want:

new URLSearchParams(params.params)

Which is sort of ugly.

So you could:

interface GetCoordsParams {
    params: Record<'city' | 'appid' | 'limit', string>;
};

export const createGetCoordsQuery = async ({ params }: GetCoordsParams) => {
    const query = new URLSearchParams(params)
    //...
}

Or:

type GetCoordsParams = Record<'city' | 'appid' | 'limit', string>;

export const createGetCoordsQuery = async (params: GetCoordsParams) => {
    const query = new URLSearchParams(params).toString();
    //...
}
  • Related