【问题标题】:Typescript custom @types package for @types/react-router用于 @types/react-router 的 Typescript 自定义 @types 包
【发布时间】:2017-08-13 23:40:18
【问题描述】:

我的项目使用打字稿做出反应。我需要使用 react-breadcrumbs 来显示 react-router 的面包屑。

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

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

react-breadcrumb 需要使用 route.props.name 来显示面包屑的名称,但是当我在 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:类型上不存在属性“名称” 'IntrinsicAttributes & IntrinsicClassAttributes> & Readonly<...>

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

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

谢谢。

【问题讨论】:

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


    【解决方案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)放在您的项目中并放置该增强接口。

    【讨论】:

    • 谢谢,我创建了一个文件 custom-route.d.ts 并放入了声明模块代码。编译成功。
    【解决方案2】:

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

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

    为什么第二个答案更短?因为它可能会花费您更少的时间来完成。

    最好的

    【讨论】:

    • 谢谢。我认为模块增强更好。因为,这个问题只是 react-router 和 react-breadcrumbs 的类型问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-09
    • 2020-01-20
    • 2020-10-30
    • 2016-11-15
    • 2016-09-29
    • 2019-12-09
    相关资源
    最近更新 更多