【问题标题】:TypeScript custom declaration files for untyped npm modules用于无类型 npm 模块的 TypeScript 自定义声明文件
【发布时间】:2017-07-30 08:22:51
【问题描述】:

我正在使用来自 npm 的名为 shiitake 的 React 组件到我使用 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] 扩充中的模块名称无效。模块 'shiitake' 解析为 'd:/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] 找不到模块“香菇”的声明文件。 'd:/dev/foo/foobar.foo.Client.Web/node_modules/shiitake/dist/index.js' 隐含了一个 'any' 类型。

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

【问题讨论】:

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


    【解决方案1】:

    声明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> { 
        }
    }
    

    【讨论】:

    • 这对您有很大帮助,谢谢。对我来说,问题在于 import 语句位于模块外部而不是内部。
    • 我希望我能投票十次。昨天我花了几个小时在这上面。我真的希望 TypeScript 文档对此更好。
    • 这么傻的问题,给出的警告也很不清楚。 VSCode 帮我搞砸了。
    • @dudewad 检查那个帖子上的用户名,看起来最多是自我抄袭(这里禁止了吗?)
    • 谢谢!我的导入在模块声明之外。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      原来我在模块声明之外粘贴了导出的接口。 我用作模板的类型文件在文件末尾有私有接口。

      所以我导出的接口是在模块声明之外声明的。 这会让 typescript 编译器发疯。

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

      【讨论】:

        猜你喜欢
        • 2017-03-06
        • 1970-01-01
        • 1970-01-01
        • 2017-02-17
        • 2020-04-09
        • 2017-07-21
        • 2019-03-21
        • 2017-06-13
        • 2015-11-22
        相关资源
        最近更新 更多