简体   繁体   English

在打字稿模块声明中重新导出符号

[英]Re-exporting symbols in a typescript module declaration

I have a private JavaScript module that I wish to write type declarations for.我有一个私有 JavaScript 模块,我希望为其编写类型声明。 The structure looks like this:结构如下所示:

.
├── index.d.ts
├── index.js
├── lib
│   ├── submodule.d.ts
│   └── submodule.js
└── package.json

In lib/submodule.d.ts :lib/submodule.d.ts

declare module 'mymodule/lib/submodule' {

    class Submodule {
        // details omitted
    }

    export = Submodule;
}

In index.d.ts I need to re-export the Submodule class from lib/submodule .index.d.ts我需要再出口的Submodule从类lib/submodule Additionally I need to document a shortcut constructor declared at the top level.此外,我需要记录在顶层声明的快捷构造函数。 Here is my attempt:这是我的尝试:

declare module 'mylib' {

    // export a `createSubmodule` function that is just a shortcut for new Submodule()
    import * as Submodule from 'mymodule/lib/submodule';
    function createSubmodule(): Submodule;

    // Also re-export Submodule
    export * as Submodule from 'mymodule/lib/submodule';
}

It seems that in index.d.ts the declaration for submodule.d.ts cannot be found.看来,在index.d.ts报关submodule.d.ts无法找到。 The message received for both the import and export is: Could not find a declaration file for module 'mymodule/lib/submodule'导入和导出都收到的消息是: Could not find a declaration file for module 'mymodule/lib/submodule'

What is the correct approach for re-exporting a symbol like this?重新导出这样的符号的正确方法是什么?

I found I needed to do two things:我发现我需要做两件事:

  1. Add inline references to the d.ts files添加对d.ts文件的内联引用
  2. Use commonjs style imports使用 commonjs 样式导入

The code becomes:代码变成:

/// <reference path="./lib/submodule.d.ts" /> // <= reference the path to the dependency

declare module 'mylib' {
    import Submodule = require('mymodule/lib/submodule'); // <= import = require()
    function createSubmodule(): Submodule;
    export * as Submodule from 'mymodule/lib/submodule';
}

Although this works I'm slightly uncomfortable about the /// directives because elsewhere in the TypeScript docs it says these should be avoided in declaration files.虽然这有效,但我对///指令有点不舒服,因为在 TypeScript 文档的其他地方,它说这些应该在声明文件中避免。 Perhaps I misunderstood that part.也许我误解了那部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM