问题描述
我从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:
在消耗方面,即使使用上面的声明,我仍然会遇到相同的错误(因为我已经打开了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';
为什么要获取此类模块的声明文件的标准是通过 @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';
应该在全局范围内.即非模块中的顶级声明(其中模块是具有至少一个顶级import
或export
的文件).
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自定义声明文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!