@ types / react-router

时间:2017-03-22 02:47:34

标签: javascript typescript react-router react-jsx typescript-typings

我的项目使用与打字稿反应。我需要使用react-breadcrumbs来显示针对react-router的Breadcrumb。

现在我将两个@type包添加到My package.json

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

react-breadcrumb需要使用route.props.name来显示breadcrumb的名称,但是当我在npm中使用@type包时 Route.d.ts文件没有在RouteProps接口中命名Props。

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;
}

所以我需要直接编辑node_modules中的Route.d.ts文件到

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

如果我没有编辑它,我将编译错误并显示

  

错误TS2339:类型中不存在属性“名称”   '内在属性& IntrinsicClassAttributes> &安培;只读< ...'

我认为直接编辑node_modules文件并不是一种好习惯。

我可以用其他方法自定义类型文件吗?

感谢。

2 个答案:

答案 0 :(得分:1)

您无需更改原始输入内容。您可以使用"模块扩充":https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation

来实现

要测试,请在导入原始模块后添加以下模块声明:

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

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

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

let x: RouteProps;

x.name; // <- no error!

现在您可以创建一个文件来将自定义类型(例如custom-typings.d.ts)放在项目中并放置该扩充界面。

答案 1 :(得分:0)

答案很长:模块增强。 https://www.infoq.com/news/2016/03/typescript1-8-released

简短回答:提交问题或在https://github.com/DefinitelyTyped/DefinitelyTyped

提交公关

为什么第二个答案更短?因为这可能会花费你更少的时间。

最佳

相关问题