// 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>>>>,
];
标签:defaultId,Typescript,const,React,Expect,inference,setId,type,id From: https://www.cnblogs.com/Answer1215/p/17636053.html