Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the initial value of the hooks cannot be given an empty object?

I have this 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>({});

I want the initial values to be an empty object.but I get error..

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

everything works with what it is connected.

like image 337
Silicum Silium Avatar asked Jan 01 '23 21:01

Silicum Silium


2 Answers

First case

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

correctly produces error. As @Shanon Jackson mentioned, faceProductList type has non-optional properties so {} is not assignable to variable of type faceProductList.

If you wish to assign, make all props of faceProductList optional with Partial<> type.

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

The second case is a way to kid TS compiler

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

Lets look at what Object is.

declare const Object: ObjectConstructor;

It is constant of type ObjectConstructor. ObjectConstructor is defined as

interface ObjectConstructor {
    new(value?: any): Object;
    (): any;
    (value: any): any;
    // ... other members
}

Take a note of function signature (): any;. So Object can be function returning variable of type any.

Now lets look at useState definition

function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];

initialState can be of type S or function returning S. As Object is also can be function but returning more general type any it can be used as argument when calling useState.

Call to Object() will return new empty object. As call signature is () => any it tells TS to not check types. And yes, as a result you'll get inital empty object but without type checking

like image 153
Fyodor Avatar answered Jan 08 '23 01:01

Fyodor


Because your telling typescript "these properties have to be defined" I.E by not putting "?" on the interface key, but then not defining them its contradictory.

You cannot have all keys as required. But then not implement them.

Hope this helps let me know if you need further information.

like image 38
Shanon Jackson Avatar answered Jan 08 '23 01:01

Shanon Jackson