问题
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