'nextjs API with typescript, restricting NextApiRequest query param to just string type [duplicate]

In this endpoint handler, is there a way to restrict req.query in NextJS NextApiRequest to just string types rather than string | string[]. For example, someQueryParam here is of string | string[] type but I want to use it as just string type

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<Response>
) {

   const { someQueryParam } = req.query;
   
   // pass in someQueryParam as a string into a function call
   const result = functionCall(someQueryParam)
}

typescript error when passing someQueryParam into a function that only accepts string type for the argument:

Argument of type 'string | string[]' is not assignable to parameter of type 'string'.
  Type 'string[]' is not assignable to type 'string'.

For reference, here is the definition of NextApiRequest in the Nextjs library

nextjs NextApiRequest

also open to any suggestions to somehow use someQueryParam as string type rather than string | string[] type within the handler before passing it into function



Solution 1:[1]

The underlining issue is that the web address protocol allows assigning of multiple query names with the same name. These then get passed as a string[] instead of a single string.

E.g, ?value=one&value=two. Therefore it should be up to the app to decide which value to accept if it's only going to make use of one string.

const value = Array.isArray(params.value) ? params.value[0] : params.value

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Casey Gibson - AOAUS