Next.js Discord

Discord Forum

TypeScript help with library function

Answered
Sphecid wasp posted this in #help-forum
Open in Discord
Sphecid waspOP
How would you give the following function a default value for the conversionFn argument while obeying the rules of TypeScript? I want the conversionFn to default to (param) => String(param) but it keeps telling me Type 'string' is not assignable to type 'T'..
export function getParam<T>(
  request: NextRequest,
  paramName: string,
  conversionFn: (param: string | null) => T
): T | undefined {
  const searchParams = request.nextUrl.searchParams;
  return searchParams.get(paramName)
    ? conversionFn(searchParams.get(paramName))
    : undefined;
}
Answered by Asian black bear
I think you have to cast the result to T as well.
View full answer

4 Replies

Asian black bear
You must restrict T using T extends string.
@Asian black bear You must restrict `T` using `T extends string`.
Sphecid waspOP
Yeah, I tried that.
export function getParam<T extends string>(
  request: NextRequest,
  paramName: string,
  conversionFn: (param: string | null) => T = (param) => String(param)
): T | undefined {
  const searchParams = request.nextUrl.searchParams;
  return searchParams.get(paramName)
    ? conversionFn(searchParams.get(paramName))
    : undefined;
}

This is still broken unfortunately. Same error. Even tried giving T a default value.
Asian black bear
I think you have to cast the result to T as well.
Answer
Sphecid waspOP
Oh man, okay. I think the one thing I didn't try was this:
export function getParam<T = string>(
  request: NextRequest,
  paramName: string,
  conversionFn: (param: string) => T = (param) => String(param) as T
): T | undefined {
  const param = request.nextUrl.searchParams.get(paramName);
  return param ? conversionFn(param) : undefined;
}

This works. Thank you 🙂