1

我正在使用react-datetime一个反应打字稿项目。我得到 TS2769 编译错误”

      TS2769: No overload matches this call.
  Overload 1 of 2, '(props: Readonly<DatetimepickerProps>): ReactDatetimeClass', gave the following error.
    Type '(inputDate: Moment) => void' is not assignable to type 'EventOrValueHandler<ChangeEvent<any>>'.
      Types of parameters 'inputDate' and 'event' are incompatible.
        Type 'string | Moment | ChangeEvent<any>' is not assignable to type 'Moment'.
          Type 'string' is not assignable to type 'Moment'.
  Overload 2 of 2, '(props: DatetimepickerProps, context?: any): ReactDatetimeClass', gave the following error.
    Type '(inputDate: Moment) => void' is not assignable to type 'EventOrValueHandler<ChangeEvent<any>>'.

以下是我的代码:

...

handleDateChange(inputdate: moment.Moment) {
    ....
}

<DateTime
 timeFormat={false}
 viewMode="days"
 closeOnSelect
 closeOnTab
 required
 onChange={this.handleDateChange}
/>

我不确定如何声明类型正确以使其编译。有什么可以帮忙的吗?

4

1 回答 1

0

您的问题是您的handleDateChange不等于所需的onChange

onChange?: EventOrValueHandler<ChangeEvent<any>>;

这是类型:

type EventOrValueHandler<Event> = (event: Event | Moment | string) => void;

如果您更新您的功能以适应这一点,那么您应该会很好。例如:

<Datetime
    timeFormat={false}
    viewMode="days"
    closeOnSelect
    onChange={
      (value: ChangeEvent | Moment | string) => {
        if ((value) && value as Moment)
          console.log("Do something with moment")
      }
    }
/>
于 2020-03-19T19:14:32.730 回答