Home > other >  How to assign a type to a list of required function arguments
How to assign a type to a list of required function arguments

Time:10-07

I have the following code

  poolContract.on(
    "Swap",
    (sender, recipient, amount0, amount1, sqrtPriceX96, liquidity, tick) => {
      console.log({
        sender: sender,
        receipient: recipient,
        amount0: ethers.utils.formatUnits(amount0, 6),
        amount1: ethers.utils.formatUnits(amount1, 18),
        sqrtPriceX96: sqrtPriceX96,
        liquidity: liquidity,
        tick: tick,
      });
    }
  );

I want to assign this type to the function arguments:

export type Swap = {
  sender: string;
  recipient: string;
  amount0: BigNumber;
  amount1: BigNumber;
  sqrtPriceX96: BigNumber;
  liquidity: BigNumber;
  tick: number;
};

When I perform

  poolContract.on(
    "Swap",
    (swap: Swap) => {
      console.log({
        sender: sender,
        receipient: recipient,
        amount0: ethers.utils.formatUnits(amount0, 6),
        amount1: ethers.utils.formatUnits(amount1, 18),
        sqrtPriceX96: sqrtPriceX96,
        liquidity: liquidity,
        tick: tick,
      });
    }
  );

The type does not get assigned. What operation can I perform to assign the function arguments the Swap type.

CodePudding user response:

How was this poolContract get initialized? Its on function might not have the correct type assertion. For example, if your poolContract is created from a class Contract like this

class Contract {
   on: (name: string, fn: () => void)
}

The swap argument in your code will not be assigned to a type

CodePudding user response:

Its okay, what I ended up doing was declaring a const in the function and enforced the type as such:

      const swap: Swap = {
        sender: sender,
        recipient: recipient,
        amount0: amount0,
        amount1: amount1,
        sqrtPriceX96: sqrtPriceX96,
        liquidity: liquidity,
        tick: tick,
      };

The poolContract.on() function comes from an external library.

  • Related