twilio / twilio-node

Node.js helper library
MIT License
1.39k stars 507 forks source link

Can't instantiate client in typescript: Only a void function can be called with the 'new' keyword #383

Closed jessep closed 6 years ago

jessep commented 6 years ago

Version: 3.19.2

Code Snippet

import * as TwilioApi from 'twilio';
const twilio = new TwilioApi('sid', 'secret');

Exception/Log

Typescript error: Only a void function can be called with the 'new' keyword 

If you don't use new keyword, the constructor doesn't get called and there's a different error. I'm just going to use the REST Api directly, but this was certainly annoying/disappointing. I'd normally just ignore it, but I'm using Google Cloud functions, and don't want to turn off their TS based safety feature, which prevents code that throws errors from deploying.

Steps to Reproduce

  1. Use typescript with twilio-node
  2. Try to instantiate a client
  3. Breaks
dkundel commented 6 years ago

Hey @jessep! I'm sorry for the caused pain.

The problem is that we are currently generating the TS bindings for the JS lib instead of writing the library in TS. The way the JS library currently is written causes the problem that we had to make the call whether the base export is a function or a class instead of both. Right now it's a function since that's technically the implementation in JS.

This means this should work:

import TwilioApi = require('twilio');
const twilio = TwilioApi('sid', 'secret');

Please let me know if this solves your problem.

Cheers, Dominik

jessep commented 6 years ago

Ha, okay, figured it out. I had already tried what you suggested, and it failed with accountSid is required. Tried it again though, and looking the line that failed, I realize that I was using the wrong token pair, not that the parameter wasn't get passed through. Thanks for the nudge!

stoplion commented 3 years ago

Is this still and issue? I am getting same error (Dec 2020)

j0hnm4r5 commented 3 years ago

I too am getting this issue as of Feb 2021. This removes the error for me:

import Twilio from "twilio";

const client = new (Twilio as any)(
    process.env.TWILIO_ACCOUNT_SID,
    process.env.TWILIO_AUTH_TOKEN
);
philnash commented 3 years ago

I have been using the Twilio library (see this post on sending SMS messages with Twilio in TypeScript) like this:

import { Twilio } from "twilio";
const client = new Twilio(accountSid, authToken);

This picks out the actual Twilio API client.