sendgrid的Typescript定义 [英] Typescript definitions for sendgrid
问题描述
我正在尝试编写一个使用sendgrid的打字稿应用程序,但与其他定义不同,我从 typings
来自 typings安装sendgrid - -ambient
让我有些头疼:
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);
然后在代码中我试图发送电子邮件,这就是为什么ts迫使我首先导入电子邮件界面。
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不会抛出任何错误,但是当我构建并运行程序时(或者只是我的测试) ),我明白了:
tslint doesn't throw any error, but when I build and run the program (or just my tests), I get this:
摩卡爆炸了!
ReferenceError:在Object处未定义Sendgrid
。 (/Users/chrismatic/codingprojects/weview/weview-node/build/server/components/mail/clients/sendgrid.js:4:13)
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
编辑:
生成的js文件如下所示:
The generated js file looks something like this:
var sendgrid = require('sendgrid');
var Email = Sendgrid.Email;
如果我对Sendgrid进行资本化,则错误消失,但我不能在ts文件
If I decapitalize "Sendgrid", then the error disappears, but I can't do so in the ts file
推荐答案
这可以让您了解如何使用SendGrid的打字稿定义。
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);
这篇关于sendgrid的Typescript定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!