首页 > 其他分享 >[React Typescript] Inferring Type Arguments in Curried Hooks

[React Typescript] Inferring Type Arguments in Curried Hooks

时间:2023-08-21 14:55:13浏览次数:46  
标签:Typescript const useMemo Hooks value React set useCustomState return

import { DependencyList, useMemo, useState } from "react";
import { Equal, Expect } from "../helpers/type-utils";

const useCustomState = <TValue>(initial: TValue) => {
  const [value, set] = useState<TValue>(initial);

  return {
    value,
    set,
    useComputed: <TFactoryReturn>(
      factory: (value: TValue) => TFactoryReturn,
      deps?: DependencyList
    ) => {
      return useMemo(() => {
        return factory(value);
      }, [value, ...(deps || [])]);
    },
  };
};

const Component = () => {
  const arrayOfNums = useCustomState([1, 2, 3, 4, 5, 6, 7, 8]);

  const reversedAsString = arrayOfNums.useComputed((nums) =>
    Array.from(nums).reverse().map(String)
  );

  type test = Expect<Equal<typeof reversedAsString, string[]>>;
};

 

标签:Typescript,const,useMemo,Hooks,value,React,set,useCustomState,return
From: https://www.cnblogs.com/Answer1215/p/17646017.html

相关文章