'Understanding Typescript code example based on uniswap code
In the uniswap website there is the following code in the Swap page (https://github.com/Uniswap/interface/blob/main/src/pages/Swap/index.tsx line 115)
const {
trade: { state: tradeState, trade },
allowedSlippage,
currencyBalances,
parsedAmount,
currencies,
inputError: swapInputError,
} = useDerivedSwapInfo()
Based on my limmited understanding of typescript what is happening is: 1) The output of useDerivedSwapInfo()
is being destructured. 2) One of the variables is trade
which has the type { state: tradeState, trade }
. But based on the further usage in the code where actually tradeState
and the 'other' trade
are being used, this makes no sense.
Could anyone help me understand this code? What does the line trade: { state: tradeState, trade }
actually do
Solution 1:[1]
- The output of
useDerivedSwapInfo()
is being destructured.
Correct!
- One of the variables is trade which has the type
{ state: tradeState, trade }
.
No, I can see how you go there but that's nested destructuring along with some renaming in the destructuring. It's taking x.trade.state
and x.trade.trade
and putting them in tradeState
and trade
respectively (where x
is the return value of useDerivedSwapInfo()
).
Here's the non-destructuring near-equivalent of that code:
const x = useDerivedSwapInfo();
const tradeState = x.trade.state;
const trade = x.trade.trade;
const allowedSlippage = x.allowedSlippage;
const currencyBalance = x.currencyBalances;
const parsedAmount = x.parsedAmount;
const currencies = x.currencies;
const swapInputError = x.inputError;
("near-equivalent" because x.trade
wouldn't actually be read twice as it is above.)
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 | T.J. Crowder |