首页 > 解决方案 > 如何在 Typescript 中扩展模块

问题描述

我正在编写一个语音识别程序。我正在@google-cloud/speech用作识别库。

好吧,我使用的语言是 Typescript(tsc 版本 3.5.3),这里的问题是没有@types/google__speech.

只要编译器建议我(否则)自己定义它,我就会这样做。我决定遵循官方文档,但只实现我现在需要的东西。所以我的代码:

declare namespace google.speech {
    export namespace types {

        interface SpeechClientOptions {
            keyFilename: string;
        }

        interface StreamingRecognitionConfig {
            config: RecognitionConfig;
            singleUtterance?: boolean;
            interimResults?: boolean;
        }
    }

    class SpeechClient {
        public constructor(opts?: types.SpeechClientOptions);
        public streamingRecognize(config: types.StreamingRecognitionConfig): NodeJS.WritableStream;
    }
}

declare module "@google-cloud/speech" {
    export = google.speech;
}

我已经缩短了上面的代码,删除了我在types命名空间中以相同方式声明的枚举和其他接口。

据我了解(如想阅读),我 1. 为@google-cloud/speech和声明一个类型 2. 还使用额外的类型定义扩展模块。这才是我真正想做的。

问题来了。我尝试导入我新创建的类型(记住,InteractionType 等已定义并且它们是枚举):

import { types } from "@google-cloud/speech";
const { InteractionType, MicrophoneDistance, RecordingDeviceType } = types;

错误:

interactionType: speech_1.types.InteractionType.VOICEMAIL,
                                            ^   
TypeError: Cannot read property 'InteractionType' of undefined

我读过几个类似的问题,但那里提到的所有东西都没有帮助我。我想我错过了一些非常基本的东西。

那么,谁能告诉我可能出了什么问题?

我想我也应该发布我的 tsconfig.json :

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "sourceMap": true,
    "noImplicitAny": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "outDir": "build/",
    "moduleResolution": "node",
    "strictNullChecks": true,
    "esModuleInterop": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}

tsc --build tsconfig.json我用我node --version的 is构建项目v12.5.0

项目结构:

./
 | - build/
 | - node_modules/
     | - @google-cloud/
         | - ...
 | - src/
     | - @types/
         | - @google-cloud__speech/
             | - index.d.ts
     | - app.ts
 | - package.json
 | - tsconfig.json

如果我错过了任何有价值的信息,请告诉我,我会添加它。

标签: typescript

解决方案


推荐阅读