使用TypeScript时,在Node.js客户端库中为Google v2上的操作扩展“conv”实例

时间:2018-05-18 07:10:41

标签: node.js typescript actions-on-google dialogflow

Google Node.js客户端库v2 上的操作中,有一个中间件,它允许向@Produces @Key public String produceKeyString() { // CDI will invoke this method in order to create bean of type String with qual. @Key String key = new String("safeKey") // replace with your logic to get the value return key; } 实例添加属性或帮助程序类。官方版本1迁移指南中的示例:

conv

这可能适用于纯JavaScript。但是如果使用 TypeScript 呢?

如果代码是用Typescript编写的,TSC会抱怨行const { dialogflow } = require('actions-on-google'); class Helper { constructor(conv) { this.conv = conv; } func1() { this.conv.ask(`What's up?`); } } const app = dialogflow() .middleware(conv => { conv.helper = new Helper(conv); }); app.intent('Default Welcome Intent', conv => { conv.helper.func1(); }); conv.helper = new Helper(conv);

  

[ts]属性'helper'在类型'DialogflowConversation< {},{},Contexts>'上不存在。

也许我可以将它重写为conv.helper.func1();,但这非常难看。有谁知道(更好)的解决方案?

1 个答案:

答案 0 :(得分:3)

dialogflow应用创建函数重载了泛型类型参数,允许您覆盖通过intent处理程序发送的Conversation类型。

您只需要创建一个扩展相应Conversation类型的类型。为了保持所有类型的安全性,它要复杂得多,但它是可行的。

因此,在大多数类型的安全和通用实现中,您在TypeScript中共享的代码段将是:

import {
  dialogflow,
  DialogflowConversation,
  DialogflowMiddleware,
  Contexts,
} from 'actions-on-google';

// an interface with the extensions to the Conversation type
interface HelperConversation<
  TData = {},
  TUserStorage = {},
  TContexts extends Contexts = {},
> extends DialogflowConversation<TData, TUserStorage, TContexts> {
  helper: Helper<TData, TUserStorage, TContexts>;
}

// the helper class now passing generic type parameters from the Conversation type
class Helper<TData, TUserStorage, TContexts extends Contexts> {
  constructor(public conv: DialogflowConversation<TData, TUserStorage, TContexts>) {}

  func1() {
    this.conv.ask(`What's up?`);
  }
}

// to keep type security in the middleware, it needs to be functional and of the DialogflowMiddleware type
const middleware: DialogflowMiddleware<HelperConversation> =
  conv => Object.assign(conv, { helper: new Helper(conv) })

// pass the extended Conversation interface into the `dialogflow` function
const app = dialogflow<HelperConversation>()
  .middleware(middleware);

app.intent('Default Welcome Intent', conv => {
  // now conv is of the type `HelperConversation`
  conv.helper.func1();
});

根据您希望TypeScript中间件的安全性/通用性,您可以使用基本的Object类型去除许多额外的泛型参数,这些参数可以减少许多代码。

您还可以查看alpha期间共享的TypeScript代码段,以获取有关使用该库的TypeScript的更详细用法: