我正在使用一个名为 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';
应该在全局范围内。即非模块中的顶级声明(其中模块是至少包含一个顶级 import
或 export
的文件)。
模块中 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/