在uniswap网站的交换页面中有以下代码(https://github.com/Uniswap/interface/blob/main/src/pages/Swap/index.tsx第115行)
const {
trade: { state: tradeState, trade },
allowedSlippage,
currencyBalances,
parsedAmount,
currencies,
inputError: swapInputError,
} = useDerivedSwapInfo()
基于我对 typescript 的有限理解,发生的情况是:1)useDerivedSwapInfo()
的输出正在被解构。 2) 其中一个变量是 trade
,其类型为 { state: tradeState, trade }
。但根据代码中实际使用 tradeState
和“其他”trade
的进一步用法,这是没有意义的。
谁能帮我理解这段代码? trade: { state: tradeState, trade }
行实际上做了什么
最佳答案
- The output of
useDerivedSwapInfo()
is being destructured.
正确!
- One of the variables is trade which has the type
{ state: tradeState, trade }
.
不,我知道你是如何去那里的,但那是嵌套解构以及解构中的一些重命名。它将 x.trade.state 和 x.trade.trade 分别放入 tradeState 和 trade 中(其中 x
是 useDerivedSwapInfo()
的返回值。
这是该代码的非解构近似等效代码:
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;
(“接近等效”,因为 x.trade
实际上不会像上面那样被读取两次。)
关于typescript - 理解基于uniswap代码的Typescript代码示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72226238/