根据道具更改状态类型 - React Typescript

Change type of state depending on props - React Typescript

我有一个表单组件“AddBooking”,它采用以下属性:

type AddBookingProps = { edit?: Booking };

如果传入这个“edit”道具,我想用设置的值渲染表单。如果没有传入,它将变成一个“创建”的空白表单。这就是我尝试使用状态的方式。

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

emptyBooking 只是 NewBooking 类型中的一组空字符串,用于初始化状态。

“Booking”和“NewBooking”类型之间的区别在于,“Booking”具有必需的“_id”类型,而“NewBooking”则没有。 我的 editBooking 和 addBooking 方法分别需要类型“Booking”和“NewBooking”。这是我收到类型错误的地方:

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

调用 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'.

有什么想法可以在没有“任何”类型的情况下解决这个问题吗? 非常感谢

这可能是类型保护的一个用例https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types

您定义的函数,用于检查 _id 是否确实在类型上。这可能是个好习惯,因为您不希望用户编辑尚不存在的预订