Search code examples
typescriptrollupreact-table

Types imported from node module becomes `any` after compilation


I'm trying to use some of the types from another package in my project API because I'm passing those params down to the mentioned package. Here is what I'm doing:

import type { Column, CellProps } from "react-table";

export const foo = (): Column => {...}

Everything works fine in the package, but when I build it using rollup, the generated .d.ts file looks like the following and the types become any when used in any consumer package (and when I hover over them in the .d.ts file):

import type { Column, CellProps } from "react-table";

export declare const foo: () => Column;

P.S. I'm using rollup for removing the declarations from the code and tsc --emitDeclarationOnly for generating those .d.ts files.

P.S.2. I have the react-table package in my dependencies which provides its built-in types (I'm not using any @types/* package)


Solution

  • This isn't quite right:

    I have the react-table package in my dependencies which provides its built-in types (I'm not using any @types/* package)

    The react-table package does not bundle its types, but rather provides them on DefinitelyTyped, via @types/react-table. If you want the consumer package to have these types, you have a few options.

    One is to make @types/react-table a dependency of your project:

    # in your project
    npm install @types/react-table
    

    Then when the consumer installs your module, they'll pull in @types/react-table as a transitive dependency. This has the downside that JavaScript users of your package will have @types dependencies that they don't need.

    Another is to have the consumer package depend on the react-table types via:

    # in consumer project
    npm install -D @types/react-table
    

    The downside of this is that your consumers have to manage this dependency themselves.

    A third option is to bundle the dependency. This is a good choice if Column and CellProps are simple interfaces. You could inline their definitions like so:

    // in your project's TS source
    export interface Column {
      // ...
    }
    
    export interface CellProps {
      // ...
    }
    
    export const foo = (): Column => {...}
    

    Assuming your declarations are compatible with the upstream declarations in react-table, TypeScript's duck typing will make this all work out.