使用 react-daterange-picker 的 Typescript 错误 "No overload matches this call."

Typescript Error using react-daterange-picker "No overload matches this call."

当我尝试在我的 React Typescript 应用程序中使用 react-daterange-picker 时,出现错误

No overload matches this call.
  Overload 1 of 2, '(props: RangeProps<DateRangePicker> | SingleProps<DateRangePicker> | Readonly<RangeProps<DateRangePicker>> | Readonly<...>): DateRangePicker', gave the following error.
    Type 'Date[]' is not assignable to type 'Moment | (MomentRange & typeof import("/Users/nyxynyx/test/node_modules/moment/ts3.1-typings/moment.d.ts")) | DateRange | undefined'.
      Type 'Date[]' is missing the following properties from type 'Moment': format, startOf, endOf, add, and 80 more.
  Overload 2 of 2, '(props: Props<DateRangePicker>, context: any): DateRangePicker', gave the following error.
    Type 'Date[]' is not assignable to type 'Moment | (MomentRange & typeof import("/Users/nyxynyx/test/node_modules/moment/ts3.1-typings/moment.d.ts")) | DateRange | undefined'.
      Type 'Date[]' is not assignable to type 'Moment'.  TS2769

    20 |         <DateRangePicker 
    21 |             onChange={onChange}
  > 22 |             value={value}
       |             ^
    23 |         />
    24 |     )
    25 | }

我的代码是基于 official example in the package repo.

为什么这里会出现 Typescript 错误,我们该如何解决?

React 打字稿代码:

import React, { useState } from 'react';
import DateRangePicker from 'react-daterange-picker';

export function Foo(): JSX.Element {

    const [ value, onChange ] = useState([new Date(), new Date()]);

    return (
        <DateRangePicker 
            onChange={onChange}
            value={value}
        />
    )
}

嗯,您从示例中更改的一行是导入。

import DateRangePicker from 'react-daterange-picker';

此行不会导入您在问题中链接到的模块。即导入 react-daterange-picker, but you linked to @wojtekmaj/react-daterange-picker。这是两个完全不同的模块。

而是安装 @wojtekmaj/react-daterange-picker 和它的类型包 @types/wojtekmaj__react-datetimerange-picker。那么它应该会像您期望的那样工作。

更改导入行

import DateRangePicker from 'react-daterange-picker';

import DateRangePicker from '@wojtekmaj/react-daterange-picker';

如果没有安装包则:

npm install @wojtekmaj/react-daterange-picker

希望对您有所帮助。谢谢。

我在@types中添加了类型定义。您可以通过 npm install --save @types/wojtekmaj__react-daterange-picke

安装它