Typescript - 获取 typeof 函数参数

标签 typescript redux

是否可以使用 TypeScript 获取函数参数的类型?

我有一个函数返回另一个返回 promise 的函数:

type login = (params: LoginParams) => dispatched
type dispatched = (dispatch: Dispatch) => Promise<any>

我想创建一个将函数作为参数的泛型类型,并创建一个新的函数类型。例如:

GenericFunctionType<login>

将创建以下类型:

(LoginParams) => Promise<any>

简而言之,GenericFunctionType 使用初始函数(登录)的参数和返回函数(调度)的返回值创建函数类型。


我想要这个是因为我正在使用 Redux。这是我的用例:

//Action Creator
export type login = (params: LoginParams) => ThunkAction<Promise<any>>;

export const login: login = params => async dispatch => {
  dispatch({ type: LOGIN });

  const promise = httpClient.post('/auth/sign_in', params);

  ...stuff

  return promise;
};

我的登录组件是这样连接的:

interface LoginProps {
  login: ???
}

class Login extends React.component<LoginProps, {}> {...}

connect(null, {login})(Login)

我正在尝试找到一种可重复使用的方式来输入已包装在 dispatch 中的 Action 创建者(这就是 connect 所做的)。

最佳答案

使用Parameters从默认库中输入


旧答案

您可以使用 tsargs为此从 npm 打包。

您的案例:

import { Arg1 } from 'tsargs';

type GenericFunctionType<F extends Function> = (params: Arg1<F>) => Promise<any>;

tsargs 示例:

import { Arg2, Args2off1, ArgsN } from 'tsargs';

function foo(a: boolean, b: number, c: string) {}

// pick specific argument
const secondArg: Arg2<typeof foo> = 123;

// pick 2 arguments skipping first
const argsBC: Args2off1<typeof foo> = [ 123, 'Hello' ];

// pick all arguments
const argsABC: ArgsN<typeof foo> = [ true, 123, 'Hello' ];

关于Typescript - 获取 typeof 函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47932200/

相关文章:

javascript - 当我尝试将 typescript 代码编译为javascript时,得到**类型 'NodeListOf<Element>'不是数组类型或字符串类型**

typescript - typescript 中枚举器的输出异常

reactjs - 使用 preloadedState : redux store gets out of sync when having a manual import of store in a function 在 React 中进行测试

javascript - Redux 状态更改后 React 容器不会重新渲染

angular - 单击按钮时如何以编程方式触发刷新 primeNG 数据表

types - 如何声明 TypeScript 导入 * 类型?

typescript - 如何调试在 vscode/vs2015 中使用 webpack 捆绑的 typescript 代码

javascript - 为什么我的 Redux reducer 重构失败了?

reactjs - 为什么在 Redux 中直接使用 "this.props.dispatch"而不是 "store.dispatch"?

javascript - 我如何将操作信息传递给组件、React + Redux?