phe*_*non 7 typescript reactjs
我正在尝试connect()在 react-redux 绑定中做一些事情。这是我在组件中注入 props 的 HOC:
export function withAdditionalProps<T, I>(
injectedProps: I,
WrappedComponent: React.ComponentType<T>,
): React.ComponentType<Omit<T, keyof I>> { ... }
Run Code Online (Sandbox Code Playgroud)
如果我声明注入的 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>)
);
Run Code Online (Sandbox Code Playgroud)
但它工作不正确:编译器在渲染组件时抛出错误。看截图(testProp是一个组件的“原生”prop)
也许任何人都可以帮助我。
简而言之,您的第二个示例在 Typescript 中尚不可能。
问题是该{ [key:string]: unknown }类型始终捕获所有可能的字符串作为键,而不是缩小到您在特定调用中使用的具体字符串,这将使Omit此处的使用成为可能。
事实上,Omit使用 with{ [key:string]: unknown }只是忽略所有可能的键,因此忽略T. 将来可能可以通过否定类型功能实现这一点,但目前唯一的方法是通过声明的类型变量,如第一个示例中所示。
但是,函数定义中声明的类型变量并不要求您为每次调用也声明它们。请参阅下面的代码 - 编译器将根据调用函数时传递的具体参数来推断T和。I因此,在实践中,这里唯一的区别在于 HOC 的类型定义,老实说,无论哪种方式,看起来都类似的工作/可读性。
function foo<T, I>(t: T, i: I): Omit<T, keyof I> {
return { ...t, ...i }
}
// notice explicitly declaring foo<{ a: number, b: number}, { c: number }>
// is NOT necessary. The correct types are just inferred from the args you pass.
const bar = foo({ a: 1, b: 2 }, { b: 3 })
bar.a // OK
bar.b // ERROR, since b is omitted
Run Code Online (Sandbox Code Playgroud)