用于非类型化npm模块的TypeScript自定义声明文件

时间:2017-03-09 11:11:35

标签: reactjs typescript ecmascript-6 visual-studio-code typescript2.0

我正在使用一个名为shiitake的React组件从npm进入我使用TypeScript的项目。该库没有TypeScript声明,所以我想我会写一个。声明文件如下所示(可能不完整,但不要太担心):

import * as React from 'react';

declare module 'shiitake' {

    export interface ShiitakeProps {
        lines: number;
    }

    export default class Shiitake extends React.Component<ShiitakeProps, any> { 
    }
}

我把它放在./typings/shiitake.d.ts文件和VS Code中,我看到以下错误:

  

[ts]扩充中的模块名称无效。模块&#39;香菇&#39;解析为一个无类型的模块:/dev/foo/foobar.foo.Client.Web/node_modules/shiitake/dist/index.js' ;,无法扩充。

在消费方面,即使使用上述声明(因为我打开了noImplicitAny编译器开关),我仍然会收到相同的错误:

/// <reference path="../../../../typings/shiitake.d.ts" />
import * as React from 'react';
import Shiitake from 'shiitake';
  

[ts]无法找到模块&#39; shiitake&#39;的声明文件。 &#39; d:/dev/foo/foobar.foo.Client.Web/node_modules/shiitake/dist/index.js'隐含地有一个“任何”的类型。

获取此类模块的声明文件的标准原因是@types/ way,并且效果很好。但是,我不能让自定义打字工作。有什么想法吗?

3 个答案:

答案 0 :(得分:70)

声明declare module 'shiitake';应该在全球范围内。即非模块中的顶级声明(模块是至少有一个顶级importexport的文件。)

模块中declare module '...' { }形式的声明是一种扩充。有关详细信息,请参阅Typescript Module Augmentation

所以你希望这个文件看起来像:

declare module 'shiitake' {

    import * as React from 'react';

    export interface ShiitakeProps {
        lines: number;
    }

    export default class Shiitake extends React.Component<ShiitakeProps, any> { 
    }
}

答案 1 :(得分:1)

我今天遇到了同样的问题。

结果我将导出的接口粘贴到模块声明之外。 我用作模板的打字文件在文件末尾有私有接口。

所以我的导出接口是在模块声明之外声明的。 这是驱动打字稿编译器的坚果。

一旦我将界面移动到模块边界,一切都得到了修复。

答案 2 :(得分:1)

根据我的经验,如果定义文件在模块定义之外声明了任何导出或者导入,则会以这种方式失败。如果您使用带自动导入的IDE,请注意!

相关问题