gpt4 book ai didi

reactjs - 为什么不能给钩子(Hook)的初始值一个空对象?

转载 作者:行者123 更新时间:2023-12-03 20:28:01 26 4
gpt4 key购买 nike

我有这个 setProd Hooks

export interface faceProduct {
readonly title: string;
readonly prodState: string;
readonly shipping: string;
readonly sold: string;
readonly alt: string;
readonly material: string;
readonly location: string;
readonly src: string[];
readonly color: string[];
readonly saiz: string[];
readonly price: string;
}

export interface faceProductList extends faceProduct {
readonly id: string;
readonly to: string;
}

const [prod, setProd] = useState<faceProductList>({});

我希望初始值是一个空对象。但我得到错误..
 const [prod, setProd] = useState<faceProductList>(Object);

一切都适用于它所连接的东西。

最佳答案

第一个案例

const [prod, setProd] = useState<faceProductList>({});

正确产生错误。正如@Shanon Jackson 所说, faceProductList type 具有非可选属性,所以 {}不能分配给 faceProductList 类型的变量.

如果您想分配,请制作 faceProductList 的所有 Prop 可选 Partial<> 类型。
const [prod, setProd] = useState<Partial<faceProductList>>({});

第二种情况是一种欺骗TS编译器的方法
const [prod, setProd] = useState<faceProductList>(Object);

让我们看看 Object is .
declare const Object: ObjectConstructor;

它是 ObjectConstructor 类型的常量. ObjectConstructordefined as
interface ObjectConstructor {
new(value?: any): Object;
(): any;
(value: any): any;
// ... other members
}

记下函数签名 (): any; .所以 Object可以是 any 类型的函数返回变量.

现在让我们看看 useState definition
function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
initialState可以是 S 类型或函数返回 S .如 Object is 也可以是函数,但返回更通用的类型 any可作为调用 useState时的参数.

调用 Object()将返回 new empty object .因为调用签名是 () => any它告诉 TS 不要检查类型。是的,结果你会得到初始的空对象,但没有类型检查

关于reactjs - 为什么不能给钩子(Hook)的初始值一个空对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56519104/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com