typescript - Make TypeScript see global types bundled by dependency
问题描述
I have a package which exposes a couple of web components. It also exposes JSX types for them so that they can be used in React without TypeScript complaining. After installing my dependency, the folder structure looks like this:
./node_modules/
my-pacakge/
src/...
index.d.ts
package.json
// package.json
{
...
"types": "./index.d.ts",
...
}
// index.d.ts
declare namespace JSX {
export interface IntrinsicElements {
'my-component': any,
'my-other-component': any,
'my-third-component': any
}
}
When I try to use <my-component></my-component>
from within JSX, I get the error Property 'my-component' does not exist on type 'JSX.IntrinsicElements'.
If I manually copy the index.d.ts
file into ./node_modules/@types/my-package/index.d.ts
then the error goes away.
If I place an import 'my-package';
anywhere in my code then the error goes away too.
I'm wondering if there is a way to get TypeScript to see my types without either publishing the module separately in the @types
repo or adding the import somewhere in my code. The web components provided by this package are commonly pulled in through a script tag, so having an explicit import of the package just so TypeScript picks up the types feels weird.
解决方案
I don't think you're going to find a better solution than just putting the import in your code.
Note that by default, TypeScript's types
mechanism automatically loads the main type declaration files of packages in the @types
scope (which on the main npm registry corresponds to DefinitelyTyped), but this feature does not apply to other packages. I believe this is because there are several DefinitelyTyped packages (e.g., @types/node
) that provide global declarations for particular target environments, and the convenience of loading these declarations without the user having to write /// <reference types="node"/>
was judged to outweigh the risk of accidents, but the same was not considered to hold for arbitrary non-@types
packages. You could try to get this mechanism to load all your packages by adding your main node_modules
directory to typeRoots
, but it's probably more sensible to just use the import.
推荐阅读
- c++ - argv 上的 const char * 与 const char **
- javascript - 在 javascript datepicker (asp.net) 中禁用过去的日期
- protractor - 用于边界值分析的量角器 Reusbale 函数
- excel - 使用 office js web 插件将 json 加载到 excel 中
- php - 关于使用 REGEX 在 PHP 中搜索字符串重合的建议
- ruby-on-rails - Rails:清理控制器中的大型方法
- javascript - 护照会话清除 req.session
- drools - 异常的一些可能原因是什么:“找不到 KieModule”?
- javascript - 使用 javascript 高阶函数简化对象转换
- python-3.x - PRNG 的种子大小(以位为单位)有什么不同吗?