小编典典

无类型npm模块的TypeScript自定义声明文件

reactjs

我从npm到我使用TypeScript的项目中使用了一个名为shiitake的React组件。该库没有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]找不到模块“
shiitake”的声明文件。’d:/dev/foo/foobar.foo.Client.Web/node_modules/shiitake/dist/index.js’隐式具有’any’类型。

为什么要获取此类模块的声明文件的标准是通过@types/方式进行的,所以效果很好。但是,我无法进行自定义键入工作。有什么想法吗?


阅读 406

收藏
2020-07-22

共1个答案

小编典典

该声明declare module 'shiitake';应在全球范围内。也就是说,非模块中的顶级声明(其中模块是具有至少一个顶级import或的文件export)。

declare module '...' { }在模块中声明表单是一种扩充。有关更多详细信息,请参见Typescript模块增强

因此,您希望此文件如下所示:

declare module 'shiitake' {

    import * as React from 'react';

    export interface ShiitakeProps {
        lines: number;
    }

    export default class Shiitake extends React.Component<ShiitakeProps, any> { 
    }
}
2020-07-22