npm 组件没有types_无类型npm模块的TypeScript自定义声明文件

当使用未提供typescript声明文件的npm组件shiiitake时,通过创建自定义的.d.ts文件来提供类型定义。然而,遇到了模块增强错误。解决方案是将declare module置于全局作用域,即在非模块(无import或export)的顶级声明中,而不是模块内。这样可以避免'any'类型的隐式错误。
摘要由CSDN通过智能技术生成

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 {

}

}

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

[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.

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):

///

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.

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?

解决方案

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).

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 {

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值