【发布时间】:2020-08-30 01:57:34
【问题描述】:
我正在尝试在 react-redux 绑定中做一些 connect() 的事情。
这是我在组件中注入 props 的 HOC:
export function withAdditionalProps<T, I>(
injectedProps: I,
WrappedComponent: React.ComponentType<T>,
): React.ComponentType<Omit<T, keyof I>> { ... }
如果我声明注入的 props 类型(I 泛型类型),它可以正常工作,但是如果我想做一个 HOC 而不声明这些类型(即时省略注入的 props 键)。如何从传递的道具中确定键?
例如,我尝试过这样的事情:
export function withAdditionalProps<T>(
injectedProps: { [key: string]: unknown },
WrappedComponent: React.ComponentType<T>,
): React.ComponentType<Omit<T, keyof typeof injectedProps>> { ... }
const InjectedComponent = withAdditionalProps<AppState>(
{
counter: 0
},
(props) => (<div>{props.counter}</div>)
);
但它不能正常工作:编译器在渲染组件时抛出错误。看截图(testProp 是一个组件的“原生”prop) 也许任何人都可以帮助我。
【问题讨论】:
-
我没能得到一个完整的版本,但是你能按照
export function withAdditionalProps<T, S extends Record<string, any>>( injectedProps: S, WrappedComponent: React.ComponentType<T>, ): React.ComponentType<Omit<T, keyof S>> { ... }做点什么吗? -
@SquattingSlavInTracksuit no,
S extends Record<string, any>这里的问题与我在下面的回答中讨论的{ [key:string]: unknown }完全相同。它将捕获所有字符串键,因此将省略T中的所有内容。使Omit以当前与 TS 的预期方式一起工作的唯一方法是使用具有声明类型变量的标准泛型。
标签: reactjs typescript