简体   繁体   English

从外部文件 React Typescript 定义 useSelector 类型

[英]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.

相关问题 如何在 React/Typescript 中定义历史和匹配类型(来自 React Router Dom) - how to define history and match type(from React Router Dom) in React/Typescript TypeScript 定义外部类 - TypeScript define external class 根据列表中对象的属性定义 Typescript 类型 - Define a Typescript type from properties of objects in a list 在 Typescript 中将类型定义为“来自枚举的所有可能性” - Define type as “all possibilities from an enum” in Typescript React Typescript,从外部脚本调用函数 - React Typescript, Call a function from external script 如何在 TypeScript 定义中定义 React FunctionalComponent 的返回类型 - How to define the return type of React FunctionalComponent in TypeScript definition 如何在 React TypeScript 中定义一次类型并将其分配给函数和组件? - How to define a type once and assign it to a function and a component in React TypeScript? React孩子是一个函数:如何正确定义TypeScript类型? - React children is a function: How to define TypeScript type correctly? 为任何 Function React Typescript 定义 prop 的类型 - Define prop's type for any Function React Typescript 在 React Typescript 中,如何为原生 html 元素定义 ...rest 参数的类型? - In React Typescript how to define type for …rest parameter for native html elements?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM