NodeJS 在typescript中为处理程序函数使用类型继承

vuktfyat  于 2023-05-17  发布在  Node.js
关注(0)|答案(1)|浏览(96)

假设我有这样的代码:

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

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

在这里,ctx参数有一个长而奇怪的类型,它为我提供了许多可访问的属性。
现在,我想改变它,让它有一个处理函数,而不使用类型AnStrangeType

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

有没有什么方法可以为处理函数的参数提供类型继承?

oprakyz7

oprakyz71#

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

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

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

相关问题