1

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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, I create a file custom-route.d.ts and put the declare module code. It's compile success.
0

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

1 Comment

thanks. I think module augmentation is better. Because, this problem is type issue only for react-router and react-breadcrumbs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.