为什么钩子的初始值不能被赋予一个空对象?

Squ*_*chy 4 typescript reactjs

我有这个 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>({});
Run Code Online (Sandbox Code Playgroud)

我希望初始值是一个空对象。但我得到错误..

 const [prod, setProd] = useState<faceProductList>(Object);
Run Code Online (Sandbox Code Playgroud)

一切都与它相连的东西一起工作。

Fyo*_*dor 7

第一种情况

const [prod, setProd] = useState<faceProductList>({});
Run Code Online (Sandbox Code Playgroud)

正确产生错误。正如@Shanon Jackson 所提到的,faceProductListtype 具有非可选属性,因此{}不可分配给 type 的变量faceProductList

如果您想分配,请faceProductList使用Partial<>type将所有 props 设为optional 。

const [prod, setProd] = useState<Partial<faceProductList>>({});
Run Code Online (Sandbox Code Playgroud)

第二种情况是一种欺骗TS编译器的方法

const [prod, setProd] = useState<faceProductList>(Object);
Run Code Online (Sandbox Code Playgroud)

让我们来看看什么Object

declare const Object: ObjectConstructor;
Run Code Online (Sandbox Code Playgroud)

它是类型常量ObjectConstructorObjectConstructor定义为

interface ObjectConstructor {
    new(value?: any): Object;
    (): any;
    (value: any): any;
    // ... other members
}
Run Code Online (Sandbox Code Playgroud)

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

现在让我们看看useState 定义

function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
Run Code Online (Sandbox Code Playgroud)

initialState可以是类型S或函数返回S。由于Object也可以是函数返回,但更普遍的类型any可以打电话时被用作论据useState

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