使用 then 方法接受声明函数的 Typescript 编码样式

Typescript coding styling with then method accepting a declared function

我正在努力处理下面代码段中使用的 typeScript 语法。有人可以帮我解决一下吗。

type Reply = (reply: Replies.AssertExchange) => string

const announce: (text: string) => Reply = (text: string): Reply => {
  return (reply: Replies.AssertExchange): string => {
    return `${text} ${(reply as Replies.AssertExchange).exchange}`
  }
}

channel.assertExchange('someName', 'fanout').then(announce('Exchange assertion'))

这里是return类型的方法channel.assertExchange() 是承诺,即 Promise<Replies.AssertExchange>

让我感到困惑的风格是,通常 .then() 函数应该采用 returned 对象,即 Replies.AssertExchange 或在 return 对象上工作的函数争论。但是,这里它采用带有字符串参数的函数,即 announce('Exchange assertion').

如果示例以正常 .then() 形式呈现就更好了。

如果您正在寻找可读性,也许 async/await 比 .then() 更好?

// Let TypeScript infer the return types and cache
// the announceExchangeAssertion function...

const announceExchangeAssertion = (
  { exchange }: Replies.AssertExchange
) => `Exchange assertion: ${exchange}`;

// Example using async/await...

foo();
async function foo() {
  const reply = await channel.assertExchange('name', 'fanout');
  announceExchangeAssertion(reply);

  // which is exactly the same as...

  announceExchangeAssertion(
    await channel.assertExchange('name', 'fanout')
  );
}

// Example using promise chaining...

channel
  .assertExchange('name', 'fanout')
  .then((reply) => announceExchangeAssertion(reply));

// Which is exactly the same as...

channel
  .assertExchange('name', 'fanout')
  .then(announceExchangeAssertion);

The style that is confusing me is, normally the .then() function should take the returned object i.e Replies.AssertExchange or a function working on the return object without arguments. However, here it's taking a function with string argument i.e announce('Exchange assertion').

announce是双箭头函数。它是一个 returns 函数(也称为“currying”)的函数。

这两个语句是一样的:

.then(announce('Exchange assertion'))
.then(reply => announce('Exchange assertion')(reply))

使用柯里化函数意味着您可以避免写出 reply => 部分。 announce('Exchange assertion') 的值正是您认为应该的值 —— 一个以 Replies.AssertExchange 作为参数的函数。

我同意 announce 函数的编写方式非常混乱。这一行特别令人费解:

const announce: (text: string) => Reply = (text: string): Reply => {

第一个: (text: string) => Reply给出变量的类型announce。它是一个接受 string 和 returns 一个 Reply.

的函数

第二个= (text: string): Reply =>是实现。

这种重复输入是没有必要的。我们可以只为实现提供类型,typescript 将能够基于此确定变量 announce 的类型。

也许这样更清楚一点:

const announce = (text: string) => 
  (reply: Replies.AssertExchange): string => 
    `${text} ${reply.exchange}`;

当您使用 text: string 调用 announce 时,您会得到一个函数 (reply: Replies.AssertExchange): string

所以announce('Exchange assertion')的类型是(reply: Replies.AssertExchange): string