我自己也不知道答案,所以我开始阅读和尝试。我的尝试非常接近,但我发现了以下缺陷:
- 两次尝试都将
initialState 显示为S 类型,而不是S | undefined,这意味着您很难在没有强制转换的情况下实现此功能。
- 第一种方案和第二种方案生成的
.d.ts不同。我相信第一次尝试的.d.ts 更接近官方的useState 定义。
- 即使您没有提及:
-
initialState 可以是一个值,也可以是一个函数,这只是第二次尝试的情况。
-
setState 函数应该有一个S | undefined 类型的参数,而不是S。
希望有更好的解决方案...
如果只有 actual implementation 是用 Typescript 编写的。
Playground
function useState<S>(initialState: S): [S, (state: S) => void];
function useState<S = undefined>(): [S | undefined, (state: S) => void];
function useState<S = undefined>(initialState?: S): [S extends undefined ? undefined | S : S, (state: S) => void] {
throw new Error(`Not implemented and not using ${initialState}`);
}
const [state1, setState1] = useState<string>("initialValue"); // string
const [state2, setState2] = useState("initialValue"); // string
const [state3, setState3] = useState<string>(); // undefined | string
const [state4, setState4] = useState(); // undefined
在操场上生成的.d.ts:
declare function useState<S>(initialState: S): [S, (state: S) => void];
declare function useState<S = undefined>(): [S | undefined, (state: S) => void];
尝试 2:没有条件类型
Playground
type Dispatch<T> = (value: T) => void;
function useState<S = undefined>(): [S | undefined, Dispatch<S | undefined>];
function useState<S>(initialState?: S | (() => S)): [S, Dispatch<S>];
function useState<S>(initialState?: S | (() => S)): [S, Dispatch<S>] {
throw new Error(`Not implemented and not using ${initialState}`);
}
const [state1, setState1] = useState<string>("initialValue"); // string
const [state2, setState2] = useState("initialValue"); // string
const [state3, setState3] = useState<string>(); // undefined | string
const [state4, setState4] = useState(); // undefined
在操场上生成的.d.ts:
declare function useState<S = undefined>(): [S | undefined, Dispatch<S | undefined>];
declare function useState<S>(initialState?: S | (() => S)): [S, Dispatch<S>];