我正在嘗試使用 Telegraf (4.6.0) 型別,但在探索可能的訊息屬性時遇到了問題。
這是我現在要做的:
import { Telegraf, Context } from 'telegraf'
const myBot = new Telegraf(myToken)
listenerBot.on('message', (ctx: Context) => {
const {
text,
forward_from_chat, forward_from_message_id,
photo, caption, caption_entities,
// what it will contain if there's a video? audio? document? ...
} = ctx.message as any
// do stuff with message
}
由于訊息可以是各種型別(在非 TS 和 TS 意義上),當我輸入ctx.message.IDE(在我的情況下為 VS Code)時,我只建議始終在訊息物件中的道具(如message_id)。是的,我可以做類似的事情
if('text' in ctx.message) {
// do stuff with ctx.message.text
}
但這并不能幫助我探索道具可以ctx.message容納什么。我可以想象一種 hacky 方式
class ExploredContext = ExploreProps<Context> → gives a class similar to Context,
but all possible props are non-optional
...
(ctx as ExploredContext).message._ // cursor here, IDE shows possilbe props
(ctx.message as ExploredMessage)._ // or like this
但我既不知道如何實作諸如ExplorePropshelper 之類的東西(我只知道實用程式型別),也不知道任何更好的、非 hacky 的方法來獲得它(比如一些打字稿和/或 IDE 的配置)。
你能建議一種實作方法ExploreProps或更好的方法來探索可能的道具嗎?
(在 Telegraf 的背景關系中,我也在一個問題中問過,但不考慮 Telegraf 本身,一致的解決方案會有所幫助)
uj5u.com熱心網友回復:
您可以使用此處StrictUnion定義的方法展平聯合。這種型別基本上會將缺少的成員添加到型別為 的所有聯合成分中。這將允許解構以建議來自任何組成部分的所有成員,但不存在于所有聯合組成部分中的每個成員也將包含(從型別安全的角度來看,這可能是最好的)undefinedundefined
import { Telegraf, Context } from 'telegraf'
type UnionKeys<T> = T extends T ? keyof T : never;
type StrictUnionHelper<T, TAll> = T extends any ? T & Partial<Record<Exclude<UnionKeys<TAll>, keyof T>, undefined>> : never;
type StrictUnion<T> = StrictUnionHelper<T, T>
const myToken = ""
const myBot = new Telegraf(myToken)
myBot.on('message', (ctx: Context) => {
const {
text,
forward_from_chat, forward_from_message_id,
photo, caption, caption_entities,
} = ctx.message as StrictUnion<Context['message']>
})
游樂場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/427174.html
