如何在 Typescript 中使用 'dialogflow' 客户端库?

How to use 'dialogflow' client library with Typescript?

我有一个可用的 Typescript 代码库,运行 服务器端在 NodeJS v10.18.0 中,我正在尝试将 'dialogflow' client library 集成到其中。

请注意,这不是对话流 webhook/fulfilment API。是客户端API.

但是我无法使用 Typescript 'dialogflow' 到 'import',即使 @types/dialogflow 声称包已经正确输入。

基本测试用例:

从某处的空文件夹开始,然后:

$ npm init     # Accept all defaults
$ tsc --init
$ npm install --save dialogflow @types/node

现在创建 index.ts 包含:

import * as df from 'dialogflow'

您可以尝试其他导入方式。他们都遇到了同样的问题。

然后尝试:

$ tsc

它抱怨:

index.ts:1:29 - error TS7016: Could not find a declaration file for module 'dialogflow'.

什么给?我做错了什么?

(我不是使用 Typescript 进行模块打字的专家)

是否为 Typescript 键入了 dialogflow?

目前唯一的选择是使用已弃用的版本。

安装

npm i -D @types/dialogflow@0.11.0

代码

import * as df from 'dialogflow';
const config = { ... };
const sessionClient = new df.SessionsClient(config);

参考this comment。希望官方库尽快修复

请注意以下选项不起作用,因为它没有正确的类型定义。

import * as dialogflow from 'dialogflow/protos/protos'

Node.js 的 Dialogflow 已将包名称更改为 @google-cloud/dialogflow,其中包含 TypeScript 定义。 https://github.com/googleapis/nodejs-dialogflow

以下是 dialogflow 1.2.0 的示例:

import * as dialogflow from 'dialogflow';
import config = require('../src/config/common.conf');

async function runSample(text: string, language: string, sessionId: string): Promise<CustomType> {
  const projectId = config.gcp.dialogflow.projectId;
  const credentials = {
    credentials: {
      private_key: config.gcp.dialogflow.privateKey,
      client_email: config.gcp.dialogflow.clientEmail,
    },
  };

  const sessionClient = new dialogflow.SessionsClient(credentials);
  const sessionPath = sessionClient.sessionPath(projectId, sessionId);
  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        text: text.slice(0, 255),
        languageCode: language,
      },
    },
  };

  const [response]: dialogflow.DetectIntentResponse[] = await sessionClient.detectIntent(request);
  return transformDialogFlowResponse(response);

}