Daniel M
Daniel M

Reputation: 143

Change type of state depending on props - React Typescript

I have a form component "AddBooking" that takes the following prop:

type AddBookingProps = { edit?: Booking };

If this "edit" prop is passed in, I want to render the form with the values set. If it isn't passed in, it becomes a "create" blank form. This is how I'm trying to use the state.

const [currentBooking, setBooking] = useState<NewBooking | Booking>(
  edit ? edit : emptyBooking
);

emptyBooking is just a load of empty strings in a NewBooking type to initialize the state.

The difference between the types "Booking" and "NewBooking" is that "Booking" has a required "_id" type whereas "NewBooking" doesn't. The methods I have for editBooking and addBooking required types "Booking" and "NewBooking" respectively. This is where I get type errors:

if (edit) {
      bookingContext.editBooking(currentBooking);
      handleClose();
    } else {
      bookingContext.addBooking({
        ...currentBooking,
        bookedBy: uContext.user.username
      });
      handleClose();
    }

I get a type error when calling editBooking:

Argument of type 'NewBooking | Booking' is not assignable to parameter of type 'Booking'. Property '_id' is missing in type 'NewBooking' but required in type 'Booking'.

Any ideas how I can get around this without the "any" type? Thanks so much

Upvotes: 1

Views: 2034

Answers (1)

Jake C
Jake C

Reputation: 134

This maybe a use case for a type guard https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types

A function you define to check that _id is actually on the type. This is probably good practice as you don't want the user to edit a booking that doesn't yet exist

Upvotes: 2

Related Questions