[英]Define useSelector type from external file React Typescript
Is there any way I could define useSelector <TRootState, string>
in external file and apply it directly inside Component's file?有什么方法可以在外部文件中定义 useSelector
<TRootState, string>
并将其直接应用到组件的文件中?
External file:外部文件:
export type TUser = <TRootState, string> // not working
Component's file:组件文件:
import { TUser } from "./pathToFile"
const user = useSelector<TUser>(selectUser)
I'm able to define the type with:我可以使用以下方式定义类型:
const user = useSelector<TRootState, string>(selectUser)
But I like to define it once and apply it in every file that needs it.但我喜欢定义一次并将其应用到每个需要它的文件中。 How it could be done?
怎么可能做到?
I've solved this in some my projects by creating a strongly typed wrapper around useSelector
that I require instead.我已经在我的一些项目中解决了这个问题,方法是围绕我需要的
useSelector
创建一个强类型包装器。
// selectors.ts
import { useSelector as reduxUseSelector } from 'react-redux'
import { StoreState } from './store'
/** Application specific strongly typed wrapper around redux's useSelector(). */
export function useSelector<T>(fn: (state: StoreState) => T): T {
return reduxUseSelector(fn)
}
Now you can just do:现在你可以这样做:
import { useSelector } from './selectors'
function Component() {
const foo = useSelector(state => state.foo) // state is typed here
//...
}
And I would then say that selectUser
should instead be a hook that calls this version of useSelector
for you.然后我会说
selectUser
应该是一个为你调用这个版本的useSelector
的钩子。
import { useSelector } from './selectors'
export function useCurrentUser(): User {
return useSelector(state => state.user)
}
function Component() {
const user = useCurrentUser()
//...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.