1

I'm wondering how to define the type for the defaultEncoder parameter. It has the same parameters as the function itself.

const paramsSerializer = (params: Params) => {
  const encoder = (
    str: string,
    defaultEncoder: any,
    charset: string,
    type: string
  ) => {
    const encodedStr = defaultEncoder(str, defaultEncoder, charset, type);
    return transformEncodedStr(encodedStr)
  };

  return transformParams(params, { encoder });
}

If I define the defaultEncoder every time it would be an infinite sequence of types.

defaultEncoder: (
  str: string,
  encoder: (
    str: string,
    encoder: // And so on...
    charset: string,
    type: "key" | "value"
  ) => any,
  charset: string,
  type: "key" | "value"
) => any,
2
  • 2
    It's easier if you extract the type: typescriptlang.org/play?#code/… Commented Apr 8, 2021 at 16:22
  • @jonrsharpe Thanks a lot. Didn't know that I can use the same type in the own type definition. Maybe you can post this as an answer so I can accept it. Commented Apr 8, 2021 at 16:30

1 Answer 1

1

As jonrsharpe said in his comment you should extract the type to a type alias to recursively use it:

type Encoder = (
  str: string,
  defaultEncoder: Encoder,
  charset: string,
  type: string
) => string;

Then you can use it in the encoder function:

const paramsSerializer = (params: Params) => {
  const encoder = (
    str: string,
    defaultEncoder: Encoder, // here
    charset: string,
    type: string
  ) => {
    const encodedStr = defaultEncoder(str, defaultEncoder, charset, type);
    return transformEncodedStr(encodedStr)
  };

  return transformParams(params, { encoder });
}

To make it simpler you can use the Encoder type in the function definition itself:

const paramsSerializer = (params: Params) => {
  const encoder: Encoder = (str, defaultEncoder, charset, type) => {
    const encodedStr = defaultEncoder(str, defaultEncoder, charset, type);
    return transformEncodedStr(encodedStr)
  };

  return transformParams(params, { encoder });
}
Sign up to request clarification or add additional context in comments.

3 Comments

If you do const encoder: Encoder = ... you don't need to reiterate all of the types of the parameters.
Yeah, that's also an option.
It's not just "an option"; it actually lets the compiler check the function is an Encoder, especially helpful as it includes the return type that's otherwise missed out.

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.