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

标签 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] Invalid module name in augmentation. Module 'shiitake' resolves to an untyped module at 'd:/dev/foo/foobar.foo.Client.Web/node_modules/shiitake/dist/index.js', which cannot be augmented.

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

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

[ts] Could not find a declaration file for module 'shiitake'. 'd:/dev/foo/foobar.foo.Client.Web/node_modules/shiitake/dist/index.js' implicitly has an 'any' type.

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

最佳答案

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

关于reactjs - 用于非类型化 npm 模块的 TypeScript 自定义声明文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42693836/

相关文章:

android - 未捕获的语法错误 : Unexpected identifier when async/await is present

javascript - 在 React 中转换对象的对象

javascript - 如何让 JSDoc 识别分配给对象属性的匿名函数? (包含示例代码)

class - 将 propTypes 和 defaultProps 作为静态 props 放入 React 类中可以吗?

javascript - Apollo-客户端自签名证书

node.js - Stripe + TypeScript : How to extend @types/stripe definitions for stripe-node?

javascript - 巴别塔 : The CLI has been moved into the package `babel-cli`

javascript - React - 如何从另一个类传递事件

reactjs - React Native - 在导航中的屏幕之间移动错误

angular - angular4 Electron 桌面应用中的sqlite3