【问题标题】:Typescript definitions for sendgridsendgrid 的打字稿定义
【发布时间】:2016-04-06 08:58:06
【问题描述】:

我正在尝试编写一个使用 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 一开始就强迫我导入电子邮件接口。

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

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

摩卡炸了! ReferenceError:未定义 Sendgrid 在对象。 (/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 文件中这样做

【问题讨论】:

    标签: javascript node.js typescript sendgrid definitions


    【解决方案1】:

    这应该让您了解如何使用 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);
      }
    
    }
    

    这是我如何使用上面的类:

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

    【讨论】:

    • 请求的响应是否是认真的Promise
    猜你喜欢
    • 2014-11-16
    • 2013-03-20
    • 2018-06-05
    • 2012-11-06
    • 2023-04-02
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多