1

我的项目使用反应与打字稿。我需要使用react-breadcrumbs来显示Breadcrumb的反应路由器。Typescript custom @types package for @ types/react-router

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

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

反应-面包屑需要使用route.props.name为面包屑显示的名字,但是当我使用@type包NPM 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:属性'name'不存在于类型 'IntrinsicAttributes & IntrinsicClassAttributes> &只读< ...'

我觉得直接编辑node_modules文件不是很好的做法。

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

谢谢。

回答

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)放在您的项目上并放置该增强界面。

+0

谢谢,我创建了一个文件custom-route.d.ts并放置了声明模块代码。这是编译成功。 –

相关问题