Typescript custom @types package for @types/react-router

試著忘記壹切 提交于 2019-12-06 14:22:01

问题


My project use react with typescript. I need to use react-breadcrumbs to show Breadcrumb for react-router.

Now I add two @type package to My package.json

 "dependencies": {
   "@types/react-breadcrumbs": "^1.3.7",
   "@types/react-router": "^3.0.8"
 }

react-breadcrumb need to use route.props.name to show name for breadcrumb, but when I use @type package in npm the Route.d.ts file has not name Props in the interface RouteProps.

interface RouteProps extends IndexRouteProps {
    path?: RoutePattern;
}
interface IndexRouteProps {
    component?: RouteComponent;
    components?: RouteComponents;
    getComponent?: (nextState: RouterState, callback: ComponentCallback) => void;
    getComponents?: (nextState: RouterState, callback: ComponentsCallback) => void;
    onEnter?: EnterHook;
    onChange?: ChangeHook;
    onLeave?: LeaveHook;
}

So I need to direct edit the Route.d.ts file in node_modules to

export interface RouteProps extends IndexRouteProps {
    path?: RoutePattern;
    name?: String;
}

If I no edit it I will compile error and show

error TS2339: Property 'name' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & Readonly<...'

I think direct edit node_modules file is not good practice.

Can I custom the type file in other method?

thanks.


回答1:


You don't need to change the original typing. You can do that using "Module Augmentation": https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation

To test, add the following module declaration after import the original module:

declare module "react-router/lib/Route" {
    interface RouteProps {
        name?: String;
    }
}

like this:

import { RouteProps } from "@types/react-router";

declare module "react-router/lib/Route" {
    interface RouteProps {
        name?: String;
    }
}

let x: RouteProps;

x.name; // <- no error!

Now you can create a file to put your custom typings (e.g. custom-typings.d.ts) on your project and put that augmentation interface.




回答2:


Long answer: module augmentation. https://www.infoq.com/news/2016/03/typescript1-8-released

Short answer: file an issue or submit a PR at https://github.com/DefinitelyTyped/DefinitelyTyped

Why is the second answer shorter? Because it will probably take you less time to do.

Best



来源:https://stackoverflow.com/questions/42941806/typescript-custom-types-package-for-types-react-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!