gpt4 book ai didi

reactjs - typescript 声明合并以扩展或覆盖模块类型或接口(interface)属性

转载 作者:行者123 更新时间:2023-12-03 14:29:57 29 4
gpt4 key购买 nike

我正在使用 @types/react-router-dom 中的类型版本 4.3.1@types/react-router 导入类型和 @types/history .

在我的应用程序中,我总是有两个处于位置状态的属性,我希望它们自动从 RouteComponentProps 中拉出。接口(interface),无需通过自定义LocationState每次向接口(interface)输入变量。
RouteComponentProps 的定义接口(interface)在react-router它如下:

import * as H from 'history';

export interface RouteComponentProps<Params extends { [K in keyof Params]?: string } = {}, C extends StaticContext = StaticContext, S = H.LocationState> {
history: H.History;
location: H.Location<S>;
match: match<Params>;
staticContext?: C;
}
history 中引用的接口(interface)/类型的定义是:
export interface Location<S = LocationState> {
pathname: Pathname;
search: Search;
state: S;
hash: Hash;
key?: LocationKey;
}

export type LocationState = History.LocationState;

export namespace History {
export type LocationState = any;
}

我想要的是扩展 Location 接口(interface)的状态属性类型定义以包含自定义接口(interface)(即包含始终可用的属性)。所以像 state: S & { A: string; B: string; } .

我试过重新声明 RouteComponentProps react-router 的模块声明中的接口(interface)但我尝试的所有结果都是 All declarations of 'RouteComponentProps' must have identical type parameters.ts(2428)Subsequent property declarations must have the same type. Property 'location' must be of type 'Location<S>', but here has type 'any'.ts(2717) .

我也尝试过重新声明 Location历史模块声明中的接口(interface)具有相同的结果。之后我尝试重新声明 LocationStateHistory 的内部和外部键入命名空间,但总是导致 Duplicate identifier 'LocationState'.ts(2300) .

我可以做些什么来获得所需的行为 除了为 RouteComponentProps 编写自定义界面之外使用不同的名称 ?我希望能够在项目中导入该接口(interface),用它扩展组件的 Prop 并拥有属性' AB可从 props.location.state 访问的类型但也能够将任何其他属性视为 any , 无需每次都传递类型变量定义 .

最佳答案

这可能不是您正在寻找的解决方案,但我通常有一个自定义位置界面(可能从您的应用程序上的共享 .ts 文件中导出它),然后使用 useLocation与该接口(interface) Hook 。

import React, { ReactElement } from "react";
import { useLocation } from "react-router-dom";

interface CustomLocationState {
A: string;
B: string;
}

export default ():ReactElement => {
const { state: {A, B} } = useLocation<CustomLocationState>();

return <div>{A} - {B}</div>
}

关于reactjs - typescript 声明合并以扩展或覆盖模块类型或接口(interface)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54924670/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com