The typing of class `SceneContextScene` is incorrect
Author: EverttCreated Apr 9, 2023Updated May 5, 2026
Labelsenhancement
Context
So I have this:
type SceneSessionData = {
current?: string
expires?: number
state?: {
lastMessageId?: number
}
}
type MyContext = Context & {
session: {
__scenes?: SceneSessionData
}
scene: Scenes.SceneContextScene<MyContext, SceneSessionData>
}And then looking at the implementation of the class SceneContextScene I see this code:
get state() {
return (this.session.state ??= {})
}
set state(value) {
this.session.state = { ...value }
}But then the type definition of the class in typings/scenes/context.d.ts shows this:
export default class SceneContextScene<C extends SessionContext<SceneSession<D>>, D extends SceneSessionData = SceneSessionData> {
// ...
get session(): D;
get state(): object;
set state(value: object);
// ...
}Which means that when I do const state = ctx.scene.state, I'd expect state to be of type { lastMessageId?: number }, because that's what it actually is, but because of the type definition state is given with type object.
Solution
Change src/scenes/context.ts to this:
export default class SceneContextScene<C extends SessionContext<SceneSession<D>>, D extends SceneSessionData = SceneSessionData> {
// ...
get session(): D;
get state(): D["state"];
set state(value: D["state"]);
// ...
}And then I assume typings/scenes/context.d.ts will automatically be generated correctly.
Source: telegraf/telegraf