0

Right now I've a little issue with a Node.js package -- Telegraf, a bot framework -- when trying to create a typing for it in TypeScript. The package itself has the following export:

module.exports = Object.assign(Telegraf, {
    Composer,
    Extra,
    Markup,
    Router,
    Telegram,
    session
})

The TS import:

import * as Telegraf from 'telegraf';

But, when trying to access it, I've the following object as Telegraf:

{ Composer: [Function: Composer],
  Extra: { [Function: Extra] Markup: [Function: Markup] },
  Markup: [Function: Markup],
  Router: [Function: Router],
  Telegram: [Function: Telegram],
  session: [Function],
  default:
  { [Function: Telegraf]
     Composer: [Function: Composer],
     Extra: { [Function: Extra] Markup: [Function: Markup] },
     Markup: [Function: Markup],
     Router: [Function: Router],
     Telegram: [Function: Telegram],
     session: [Function] } }

My doubt is: How can I access the [Function: Telegraf] in Telegraf.default?

Note

You might ask "Why he wants to access this expecific property?". It's because I've to emulate the following Node.js in TS:

const Telegraf = require('telegraf');

const bot = new Telegraf(process.env.BOT_TOKEN);

More about Telegraf in: http://telegraf.js.org/#/

  • I don't recognize that syntax because I'm not a TypeScript user, but there is no such thing in JavaScript as an object property without a name. – Pointy Mar 18 '18 at 13:55
  • Have a look at: https://stackoverflow.com/questions/29596714/new-es6-syntax-for-importing-commonjs-amd-modules-i-e-import-foo-require – brentatkins Mar 18 '18 at 15:46
  • you should be able to use `import Telegraf = require('telegraf')` – brentatkins Mar 18 '18 at 15:47
  • @brentatkins thanks a lot, this helped me out understand the "real" problem. The funny thing is that when I was searching for it, I didn't find this answer if I had wouldn't have open this question. – Lucas Almeida Carotta Mar 18 '18 at 16:02

1 Answers1

0

Very weird this [Function: Telegraf] is shown without a key/name because that is an invalid object.

However, assuming the default object is valid and only has that function plus these keys ['Extra', 'Markup', 'Router', 'Telegram', 'session'] an alternative is filtering those keys and executing the function related to the filtered key:

let key = Object.keys(Telegraf.default)
                .filter(k => !['Extra', 'Markup', 'Router', 'Telegram', 'session'].includes(k));

Telegraf.default[key.pop()]() // <-- Execute the function!
Ele
  • 33,468
  • 7
  • 37
  • 75
  • Thanks! This helped me a lot because when trying to do this the JS raise a warning saying that it was a class constructor and I shouldn't be using without a **new**... Just using Telegraf.default() without the [key.pop()] did the job. – Lucas Almeida Carotta Mar 18 '18 at 14:06