首页 > 解决方案 > 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.

标签: typescript

解决方案


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.


推荐阅读