[React Typescript] Fixing type inference in a Custom React Hook

发布时间 2023-08-16 19:54:41作者: Zhentiw
// Problem
import { useState } from "react";
import { Equal, Expect } from "../helpers/type-utils";

export const useId = (defaultId: string) => {
  const [id, setId] = useState(defaultId);

  return [id, setId];
};

const [id, setId] = useId("1");

type tests = [
  Expect<Equal<typeof id, string>>,
  Expect<Equal<typeof setId, React.Dispatch<React.SetStateAction<string>>>>
];

the return type is actually:

(string | React.Dispatch<React.SetStateAction<string>> | undefined)[]

 

Two way to solve the problem:

1. Force the return type for the hook: not great, but working

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

export const useId = (
  defaultId: string,
): [string, React.Dispatch<React.SetStateAction<string>>] => {
  const [id, setId] = useState(defaultId);

  return [id, setId];
};

const [id, setId] = useId("1");

type tests = [
  Expect<Equal<typeof id, string>>,
  Expect<Equal<typeof setId, React.Dispatch<React.SetStateAction<string>>>>,
];

 

2. using as const

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

export const useId = (defaultId: string) => {
  const [id, setId] = useState(defaultId);

  return [id, setId] as const;
};

const [id, setId] = useId("1");

type tests = [
  Expect<Equal<typeof id, string>>,
  Expect<Equal<typeof setId, React.Dispatch<React.SetStateAction<string>>>>,
];