Nepo Znat
Nepo Znat

Reputation: 3280

Self referencing function in TypeScript?

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,

Upvotes: 1

Views: 64

Answers (1)

blaumeise20
blaumeise20

Reputation: 2220

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

Upvotes: 1

Related Questions