我正在尝试键入一个useStateUpdater
React Hook,它将带有一个初始状态,一个咖喱函数将首先提供当前状态,其次提供一个可选参数。
有效用法是:
const [state, toggle] = useStateUpdater(false, bool => () => !bool);
toggle();
console.log(state); // true
或
const [str, append] = useStateUpdater('foo', str => more => str + more);
append('bar');
console.log(str); // 'foobar'
这是我的钩子代码,到目前为止,我可以定义这些类型:
// @flow
import { useState } from 'react';
type UseStateUpdater = <S, U>(
initialState: (() => S) | S,
updater: U
) => [S, any => void];
const useStateUpdater: UseStateUpdater = ((initialState, updater) => {
const [state, setState] = useState(initialState);
return [state, (...args) => setState(state => updater(state)(...args))];
}: any);
export default useStateUpdater;
一切正常,但问题在于,此刻返回的updater
函数具有any
作为参数类型。
我希望它在第二个函数上具有U
类型的类型作为参数。
useStateUpdater(S, S => ARGS => S);
^
How do I reference this?
作为伪代码,类型应类似于:
type UseStateUpdater = <S, U>(
initialState: (() => S) | S,
updater: U
) => [S, (...args: $Arguments<$ReturnType<typeof U>>) => void];
想法?
答案 0 :(得分:0)
我想出了如何键入它:
// @flow
import { useState } from 'react';
type UseStateUpdater = <S, U>(
initialState: (() => S) | S,
updater: S => U => S
) => [S, U => void];
const useStateUpdater: UseStateUpdater = ((initialState, updater) => {
const [state, setState] = useState(initialState);
return [state, (...args) => setState(state => updater(state)(...args))];
}: any);
export default useStateUpdater;