Tous les articles
Development31 mai 20261 minute de lecture

Why I use TypeScript for all my Telegram bot projects.

Why I use TypeScript for all my Telegram bot projects.

Developing interactive robots involves manipulating many variations of asynchronous requests in the background. Using standard JavaScript can quickly lead to unhandled anomalies. This is why TypeScript has become my absolute standard.

The assurance of precise and strict typing

Telegram's Webhooks return complex structures (composed of message redirections, annotations, voice inputs, or payments). Thanks to built-in type definitions from reputable libraries like grammY or Telegraf, your environment instantly suggests available properties:

  • Static validation of the presence of variables (avoids TypeError: cannot read property of undefined).
  • Intelligent autocompletion of all query fields in Visual Studio Code or IntelliJ.
  • Heavy refactoring made ultra-simplified by renaming properties without fear of breaking remote modules.

Example of a typed implementation

import { Bot, Context } from 'grammy';

interface CustomContext extends Context {
  session: {
    stepsCompleted: number;
  };
}

const bot = new Bot<CustomContext>('TELEGRAM_BOT_SECRET_TOKEN');

bot.command('welcome', async (ctx) => {
  const username = ctx.from?.first_name ?? 'Developer';
  await ctx.reply(`Welcome, ${username} ! You are at the stage ${ctx.session?.stepsCompleted || 0}.`);
});

bot.start();

Leveraging generic interfaces makes your architecture exceptionally clean.

La publicitรฉ permet de garder ce blog gratuit.

Discussion (0)

Join the discussion!

To post a comment or share your thoughts on this article, sign in securely in one click with your Google account.

Loading discussion...