使用类型继承来创建 TypeScript 中的处理函数

huangapple go评论57阅读模式
英文:

Using type inheritance for a handler function in typescript

问题

Here's the translated code portion:

假设我有以下代码

```javascript
import { Telegraf } from "telegraf";
const bot = new Telegraf(process.env.BOT_TOKEN || "");

bot.on("text", async (ctx) => {
  console.log(ctx.message?.text);
});

在这里,ctx 参数具有一个长而奇怪的类型,可以访问许多属性。

现在,我想将其更改为使用类型 AnStrangeType 的处理函数:

async function handleMessage(ctx: AnStrangeType): Promise<void> {
  console.log(ctx.message?.text);
}
bot.on("text", handleMessage);

是否有一种方式可以实现处理函数的参数的类型继承?


<details>
<summary>英文:</summary>

Assume I have this code:

import { Telegraf } from "telegraf";
const bot = new Telegraf(process.env.BOT_TOKEN || "");

bot.on(message("text"), async (ctx) => {
console.log(ctx.message?.text);
});


Here, the `ctx` parameter has an long and strange type that gives me lots of props accessible.

Now, I want to change it to have a handler function without using the type `AnStrangeType`:

async function handleMessage(ctx: AnStrangeType): Promise<void> {
console.log(ctx.message?.text);
}
bot.on(message("text"), handleMessage);


is there any way to have something like type inheritance for the arguments of the handler function?

</details>


# 答案1
**得分**: 1

```ts
import { Telegraf } from "telegraf";
const bot = new Telegraf(process.env.BOT_TOKEN || "");

bot.on('message', async (ctx) => {
    console.log(ctx.message?.text);
});

// 选取所需的通用调用。
// 这里可能需要 `<typeof message("text")>` 的通用类型,我不知道 `message` 函数是什么
type call = typeof bot.on<'message'>
// 第二个参数是你要找的函数
type arg = Parameters<call>[1]
// 创建该类型的变量
const handleMessage: arg = async (ctx) => {
    console.log(ctx.message?.text);
}
英文:
import { Telegraf } from &quot;telegraf&quot;;
const bot = new Telegraf(process.env.BOT_TOKEN || &quot;&quot;);

bot.on(&#39;message&#39;, async (ctx) =&gt; {
    console.log(ctx.message?.text);
});

// pick the selected generic call.
// You may need `&lt;typeof message(&quot;text&quot;)&gt;` generic here, I dunno what&#39;s `message` function
type call = typeof bot.on&lt;&#39;message&#39;&gt;
// 2nd arg is the function you are looking for
type arg = Parameters&lt;call&gt;[1]
// make a variable of that type
const handleMessage: arg = async (ctx) =&gt; {
    console.log(ctx.message?.text);
}

huangapple
  • 本文由 发表于 2023年5月15日 04:22:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76249521.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定