我想创建一个包装器功能useStateRO,它将所有属性标记为只读,以便只能使用setState更改状态,但不能为返回值创建正确的类型。
代码沙盒示例。
import React, { useState, useEffect } from "react";
import { render } from "react-dom";
type DeepReadonly<T> = T extends (infer R)[]
? DeepReadonlyArray<R>
: T extends Function
? T
: T extends object
? DeepReadonlyObject<T>
: T;
function useStateRO<T>(
props: T
): [DeepReadonly<T>, React.Dispatch<React.SetStateAction<T>>] {
return useState<DeepReadonly<T>>(props); // fix needed
}
interface IX {
x: number;
}
function App() {
const [test, setTest] = useState<IX>({ x: 1 });
useEffect(() => {
setTest({ x: 2 });
}, []);
console.log(test.x);
test.x = 5; // should be error
return <div>Hi</div>;
}
render(<App />, document.getElementById("root"));
与往常一样,在制作沙盒并提出问题后自己找到解决方案:/
function useStateRO<T>(props: T): [DeepReadonly<T>, React.Dispatch<React.SetStateAction<T>>] {
return useState(props) as [DeepReadonly<T>, React.Dispatch<React.SetStateAction<T>>]
}