针对@ types / react-router的Typescript自定义@types包 [英] Typescript custom @types package for @types/react-router

查看:783
本文介绍了针对@ types / react-router的Typescript自定义@types包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My project use react with typescript. I need to use react-breadcrumbs to show Breadcrumb for react-router.

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

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

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

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

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


错误TS2339:类型
'属性'名称'不存在'IntrinsicAttributes& IntrinsicClassAttributes>& Readonly< ...'

error TS2339: Property 'name' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & Readonly<...'

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

I think direct edit node_modules file is not good practice.

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

Can I custom the type file in other method?

谢谢。

推荐答案

您无需更改原始输入。您可以使用模块增强来执行此操作: https:// www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation

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

这样:

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

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.

这篇关于针对@ types / react-router的Typescript自定义@types包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆