Search code examples
node.jstypescriptnext.jsrequest

URLSearchParam type {property: value} is not assignable to undefined & Argument Type {property: value} not assignable to {property: value}


I keep getting this error when I try to execute the following code. Basically it takes in the given refresh token and send a POST request with the URLSearchParams to the URL. But for some reason URLSearch params keeps on throwing an error.

enter image description here

Code

const getAccessToken = async () => {
  const response = await fetch(TOKEN_ENDPOINT, {
    method: 'POST',
    headers: {
      Authorization: `Basic ${basic}`,
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: new URLSearchParams({
      grant_type: 'refresh_token',
      refresh_token,
    }),
  })
  return response.json()
}

where refresh_token is a constant defined by an enviornment variable.

Error

Argument of type '{ grant_type: string; refresh_token: string | undefined; }' is not assignable to parameter of type 'string | string[][] | Record<string, string> | URLSearchParams | undefined'.
  Type '{ grant_type: string; refresh_token: string | undefined; }' is not assignable to type 'undefined'.ts(2345)

Solution

  • The problem is that refresh_token is potentially undefined and URLSearchParams only supports fields with string values.

    There are several options here...

    1. Provide a fallback string value

      new URLSearchParams({
        grant_type: "refresh_token",
        refresh_token: refresh_token ?? ""
      })
      
    2. Add parameters optionally

      const body = new URLSearchParams({ grant_type: "refresh_token" });
      if (refresh_token) {
        body.append("refresh_token", refresh_token);
      }
      
    3. If you're sure that refresh_token is not undefined, assert it as so

      new URLSearchParams({
        grant_type: "refresh_token",
        refresh_token: refresh_token!
      })