Search code examples
reactjstypescripttypescript2.0react-bootstrap-table

Extend TypeScript 2.5.2 Component Props definition in a separate definition file


I have downloaded a NPM package called react-bootstrap-table with type definitions.

https://www.npmjs.com/package/react-bootstrap-table

https://www.npmjs.com/package/@types/react-bootstrap-table

Unfortunately the types are outdated and a prop called strictSearch is missing from BootstrapTable definitions that I need. I can of course update the definitions in node_modules but we are a team working on this project and we are not committing the node_modules folder.

I have read the thread here but I can't get it working anyway:

How do I extend a TypeScript class definition in a separate definition file?

How can I get it working?

If I add a new folder called for example "react-bootstrap-table-ex" everything looks good but of course I have no corresponding module for that.

Module not found: Error: Can't resolve 'react-bootstrap-table-ex'

If I rename my folder to react-bootstrap-table the types are only loaded from my new index.d.ts file and I cant reference the original definitions. I then tried to set the path for the original definitions manually but again the Module not found error occurs.

Module not found: Error: Can't resolve '../../../node_modules/@types/react-bootstrap-table'

Code:

import { ComponentClass, Props } from "react";
import { BootstrapTableProps, BootstrapTable } from '../../node_modules/@types/react-bootstrap-table';

export interface BootstrapTableExProps extends BootstrapTableProps {
    strictSearch?: boolean;
}

export interface BootstrapTableEx extends ComponentClass<BootstrapTableExProps> {

}

declare const BootstrapTableEx: BootstrapTableEx;

Solution

  • Use Module Augmentation to extend existing typings. Create .ts file with the following code

    import { BootstrapTableProps, BootstrapTable } from 'react-bootstrap-table';
    
    declare module "react-bootstrap-table" {
      export interface BootstrapTableExProps extends BootstrapTableProps {
        strictSearch?: boolean;
      }
    
      export interface BootstrapTableEx extends ComponentClass<BootstrapTableExProps> {
    
      }
    }
    

    New typings will be available in the entire project.

    You can find more info here https://www.typescriptlang.org/docs/handbook/declaration-merging.html under Module Augmentation section.