是否可以使用 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/