首页 > 其他分享 >[React Typescript] Function overload in React hook

[React Typescript] Function overload in React hook

时间:2023-08-21 14:44:20浏览次数:57  
标签:Function Typescript const React useStateAsObject set Expect type

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

type UseStateReturnValue<T> = {
  value: T;
  set: React.Dispatch<React.SetStateAction<T>>;
};

export function useStateAsObject<T>(): UseStateReturnValue<T | undefined>;
export function useStateAsObject<T>(initial: T): UseStateReturnValue<T>;
export function useStateAsObject<T>(initial?: T) {
  const [value, set] = useState(initial);

  return {
    value,
    set,
  };
}

const notUndefined = useStateAsObject({ name: "Matt" });

type ExampleTests = [
  Expect<Equal<typeof notUndefined.value, { name: string }>>,
  Expect<
    Equal<
      typeof notUndefined.set,
      React.Dispatch<React.SetStateAction<{ name: string }>>
    >
  >,
];

const hasUndefined = useStateAsObject<number>();

type NumTests = [
  Expect<Equal<typeof hasUndefined.value, number | undefined>>,
  Expect<
    Equal<
      typeof hasUndefined.set,
      React.Dispatch<React.SetStateAction<number | undefined>>
    >
  >,
];

 

标签:Function,Typescript,const,React,useStateAsObject,set,Expect,type
From: https://www.cnblogs.com/Answer1215/p/17645991.html

相关文章