sendgrid 的打字稿定义

Typescript definitions for sendgrid

我正在尝试编写一个使用 sendgrid 的打字稿应用程序,但与我从 typings 获得的其他定义不同,来自 typings install sendgrid --ambient 的定义让我有些头疼:

我可以像这样实例化客户端:

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

然后在代码的后面我尝试发送电子邮件,这就是为什么 ts 首先强制我导入 EMail 接口的原因。

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

tslint 不会抛出任何错误,但是当我构建并 运行 程序(或只是我的测试)时,我得到了这个:

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

是否有人可以展示有效的实现,或者我必须编写自己的界面?在此先感谢您的帮助

编辑:

生成的 js 文件如下所示:

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

如果我取消大写"Sendgrid",那么错误就消失了,但是我在ts文件中做不到

这应该会让您了解如何使用 SendGrid 的打字稿定义。

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);
  }

}

下面是我如何使用上面的 class:

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);