[SOLVED] Having issues using Pick utility type with React useState hook

Issue

I’m trying to understand why can’t I use Pick utility type to pick one property from my interface and use it to type my component’s state.

Here’s the interface:

export interface IBooking {
  ...
  propertyId: string | null;
  ...
}

And then in my component I have the following:

const [propertyId, setPropertyId] = useState<Pick<IBooking, 'propertyId'>>('some-id');

This is the error I get:

TS2345: Argument of type 'string' is not assignable to parameter of type 'Pick  | (() => Pick )'.

However, if I just replace Pick<IBooking, 'propertyId'> with string | null, it, of course, works. And I don’t understand what is the difference. Isn’t it exactly what Pick type should do? I didn’t have much experience with utility types, but I’m using Pick type perfectly fine in another place. Is it because some specifics of useState hook?

What am I missing here?

Thanks in advance.

Solution

Assuming that propertyId on IBooking is of the type string | null then it will be the following type:

{
    propertyId: string | null;
}

The result of Pick is an object containing only attributes which are listed.

You can use a lookup type like this instead:

IBooking["propertyId"]

Answered By – Timothy L Gillespie

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *