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並放置了聲明模塊代碼。這是編譯成功。 –

相關問題