用于无类型npm模块的TypeScript自定义声明文件 [英] TypeScript custom declaration files for untyped npm modules

查看:469
本文介绍了用于无类型npm模块的TypeScript自定义声明文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从npm到我使用TypeScript的项目中使用了一个名为 shiitake 的React组件.该库没有TypeScript声明,所以我想我会写一个.声明文件如下所示(它可能不完整,但不必担心太多):

I am consuming a React component called shiitake from npm into my project where I use TypeScript. That library does not have TypeScript declarations so I thought I would write one. The declaration file looks like below (it may not be complete but don't worry about it too much):

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上,看到以下错误:

I have put this inside ./typings/shiitake.d.ts file and on VS Code, I am seeing the below error:

[ts]扩充中的模块名称无效.模块'shiitake'解析为'd:/dev/foo/foobar.foo.Client.Web/node_modules/shiitake/dist/index.js'上的无类型模块,该模块无法扩充.

[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编译器开关):

On the consumption side, I am still getting the same error even if with the above declaration (since I have noImplicitAny compiler switch turned on):

/// <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"类型.

[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/方式,并且效果很好.但是,我无法进行自定义键入工作.有什么想法吗?

The standard why of acquiring declaration files for this type of modules is through @types/ way and it works well. However, I cannot get the custom typings work. Any thoughts?

推荐答案

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

The declaration declare module 'shiitake'; should be in a global scope. i.e. a top level declaration in a non module (where a module is a file with at least one top level import or export).

模块中形式为declare module '...' { }的声明是增强.有关更多详细信息,请参见 Typescript模块增强.

A declaration of the form declare module '...' { } in a module is an augmentation. For more details see Typescript Module Augmentation.

因此,您希望此文件看起来像这样:

So you want this file to look like:

declare module 'shiitake' {

    import * as React from 'react';

    export interface ShiitakeProps {
        lines: number;
    }

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

这篇关于用于无类型npm模块的TypeScript自定义声明文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆