通用 Typescript Type + React hook

IT技术 reactjs typescript react-hooks typescript-generics use-reducer
2021-05-22 10:56:42

我有以下 http 钩子:

export const useHttp = <T,>(initUrl: string, initData: T) => {
    const [url, setUrl] = useState(initUrl);
    const [state, dispatch] = useReducer(fetchReducer, {
        isLoading: false,
        error: '',
        data: initData
    });

    useEffect(() => {
        let cancelRequest = false;

        const fetchData = async (cancelRequest: boolean = false) => {
            if (!url) return;

            dispatch({ type: 'API_REQUEST'});
            try {
                const responsePromise: AxiosPromise<T> = axios(url);
                const response = await responsePromise;
                if (cancelRequest) return;
                dispatch({ type: 'API_SUCCESS', payload: response.data });
            } catch (e) {
                console.log("Got error", e);
                dispatch({ type: 'API_ERROR', payload: e.message });
            }
        };
        fetchData(cancelRequest);

        return () => {
            cancelRequest = true;
        }

    }, [url]);

    const executeFetch = (url: string) => {
        setUrl(url);
    };

    return { ...state, executeFetch}
};

减速器:

const fetchReducer = <T,>(state: IState<T>, action: TAction<T>): IState<T> => {
    switch (action.type) {
        case 'API_REQUEST':
            return {
                ...state,
                isLoading: true
            };
        case 'API_SUCCESS':
            return {
                ...state,
                data: action.payload,
                isLoading: false,
                error: ''
            };
        case 'API_ERROR':
            console.error(`Triggered: ${API_ERROR}, message: ${action.payload}`);
            return {
                ...state,
                error: action.payload,
                isLoading: false,
            };
        default:
            throw Error('Invalid action');
    }
};

行动:

export interface IApiSuccess<T> {
    type: types.ApiSuccess,
    payload: T;
}
export type TAction<T> = IApiRequest | IApiSuccess<T> | IApiError;

像这样使用:

const { data, error, isLoading, executeFetch } = useHttp<IArticle[]>('news', []);

return (
        <>
            <div className={classes.articleListHeader}>
                <h1>Article List</h1>
                <small className={classes.headerSubtitle}>{data.length} Articles</small>
            </div>
            <ul>
                {data.map(article => <Article article={article}/>)}
            </ul>
        </>
    )

我的 TS 对我大喊大叫,因为我正在使用data变量:Object is of type 'unknown'. TS2571

我确实指定了 useHttp 的类型,即 IArtlce[]。知道我错过了什么吗?

更新:我尝试为我的减速器添加返回类型:

interface HttpReducer<T> extends IState<T> {
    executeFetch: (url: string) => void
}

export const useHttp = <T,>(initUrl: string, initData: T): HttpReducer<T> => {

但我得到:

Type '{ executeFetch: (url: string) => void; error: string; isLoading: boolean; data: unknown; }' is not assignable to type 'HttpReducer<T>'.
1个回答

我能够重现您的错误您期望useReducer钩子能够根据初始状态的类型推断状态类型,但它只是推断IState<unknown>.

for 的类型useReducer 被定义为泛型参数是reducer 的类型。状态的类型是从具有ReducerState实用程序类型的减速器推断出来的它不期望通用减速器并且不能很好地使用它。

T挂钩的 和T减速器的之间没有关系,而不是状态。 fetchReducer是一个泛型函数,这意味着它可以接受any IState并返回IState相同类型的an 我们可以使用这个函数来处理IState<T>我们钩子的 ,但是为了推断状态的类型,我们需要说我们的函数只会接受和返回IState<T>

您需要将通用设置为useReducer

const [state, dispatch] = useReducer<(state: IState<T>, action: TAction<T>) => IState<T>>( ...

从表面上看,这与现在推断的非常相似,即:

const [state, dispatch] = useReducer<<T,>(state: IState<T>, action: TAction<T>) => IState<T>>(...

但差异至关重要。当前描述了一个通用函数,而修复描述了一个只采用一种类型的函数T——useHttp钩子的类型。这是误导,因为您同时使用T两者。也许我们重命名一个更容易看出。

我们一个通用函数:

export const useHttp = <Data,>(initUrl: string, initData: Data) => {
  const [url, setUrl] = useState(initUrl);
  const [state, dispatch] = useReducer<<T,>(state: IState<T>, action: TAction<T>) => IState<T>>(fetchReducer, {

我们需要该函数的特定用例:

export const useHttp = <Data,>(initUrl: string, initData: Data) => {
  const [url, setUrl] = useState(initUrl);
  const [state, dispatch] = useReducer<(state: IState<Data>, action: TAction<Data>) => IState<Data>>(fetchReducer, {

当我们知道我们的减速器状态类型是 时IState<Data>,我们就知道类型dataData

现在调用useHttp<IArticle[]>()为您提供了一个data类型为的变量IArticle[]

typescript游乐场链接