// 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>>>>,
];
- React Typescript inference Fixing Customreact typescript inference fixing typescript forwardref fixing react typescript inferring literal basic typescript inferring arguments curried componentprops typescript inference satisfies typescript inference multiple generic extracting components typescript custom discriminated typescript custom tuples typescript workspace monorepo react typescript component strongly react