javascriptnode.jstypescriptsendgriddefinitions

Typescript definitions for sendgrid


I am trying to write a typescript app that uses sendgrid, but unlike with other definitions I got from typings the one from typings install sendgrid --ambient is causing me some headaches:

I am able to instantiate the client like so:

import * as sendgrid from 'sendgrid';
import Email = Sendgrid.Email;
import Instance = Sendgrid.Instance;
...
private client: Instance;
...
this.client = sendgrid(user, key);

And then later in the code I am trying to send an email, which is why ts is forcing me to import the EMail interface in the first place.

var email = new Email();
...
this.client.send(email, (err, data) => {
        if (err) {
            throw err;
        }
    });

tslint doesn't throw any error, but when I build and run the program (or just my tests), I get this:

Mocha exploded! ReferenceError: Sendgrid is not defined at Object. (/Users/chrismatic/codingprojects/weview/weview-node/build/server/components/mail/clients/sendgrid.js:4:13)

Has anybody a working implementation to showcase, or do I have to write my own interface? Thanks in advance for the help

EDIT:

The generated js file looks something like this:

var sendgrid = require('sendgrid');
var Email = Sendgrid.Email;

If I decapitalize "Sendgrid", then the error disappears, but I can't do so in the ts file


Solution

  • This should give you an idea on how to use SendGrid's typescript definitions.

    import * as SendGrid from 'sendgrid';
    
    export class SendGridMail extends SendGrid.mail.Mail {}
    export class SendGridEmail extends SendGrid.mail.Email {}
    export class SendGridContent extends SendGrid.mail.Content {}
    
    export class SendGridService {
      private sendGrid;
    
      constructor(private sendgridApiKey: string) {
        this.sendGrid = SendGrid(sendgridApiKey);
    
      }
    
      send(mail: SendGridMail): Promise<any> {
    
        let request = this.sendGrid.emptyRequest({
          method: 'POST',
          path: '/v3/mail/send',
          body: mail.toJSON()
        });
    
        return this.sendGrid.API(request);
      }
    
    }
    

    Here is how I used the class above:

    let mail = new SendGridMail(
          new SendGridEmail('from@example.com'),
          'Sending with SendGrid is Fun',
          new SendGridEmail('to@example.com'),
          new SendGridContent('text/plain', 'Email sent to to@example.com'));
    
    
    return this.sendgridService.send(mail);