1

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'.

2 Answers 2

1

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();
    //...
}
Sign up to request clarification or add additional context in comments.

Comments

0

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();
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.