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

2024-01-10

我正在使用一个名为的 React 组件shiitake https://github.com/bsidelinger912/shiitake从 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] 增强中的模块名称无效。模块“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/ way https://blog.mariusschulz.com/2016/10/23/typescript-2-0-acquiring-type-declaration-files而且效果很好。但是,我无法让自定义打字工作。有什么想法吗?


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

表格声明declare module '...' { }模块中是一个增强。欲了解更多详情,请参阅Typescript 模块增强 https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation.

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

declare module 'shiitake' {

    import * as React from 'react';

    export interface ShiitakeProps {
        lines: number;
    }

    export default class Shiitake extends React.Component<ShiitakeProps, any> { 
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

非类型化 npm 模块的 TypeScript 自定义声明文件 的相关文章

随机推荐