无法让打字稿识别打字

时间:2021-06-01 18:56:08

标签: typescript types react-datepicker

我正在处理这个项目,我们需要将所有从 React Javascript 创建的文件转换为 React Typescript,但作为类型注释的初学者,我遇到了一些困难,尤其是 3rd 方包和库。

我正在使用 ReactDatePicker 来获取用户输入的日期(写入的或选择的)和用于解析它的时刻库,以及多步表单中的 formik,因此用户可以在一个组件中查看、编辑和创建所有内容。在我篡改的最新文件中,打字稿抱怨我正在使用的“字符串”值无法分配给“日期”,尽管我将其输入为“日期” |当我编码时,它的界面上的字符串。

这是接口,在一个外部文件中:

export interface BaseRelationType extends BaseEntity {
  institutional_relation_approval: Date | string | any,
}

这是访问它的组件:

import {
  getIn, useFormikContext,
} from 'formik';
import DatePicker from 'react-datepicker';
import { FormikStep } from 'components/Stepper/Step';
import DateInput, { DateInputProps } from 'components/DateInput/DateInput';
import { RelationFormType } from 'types/relations';

export interface DateStepProps {
  validationSchema: Object,
  innerRef: boolean,
}

const RelationTypeStep: React.FC<DateStepProps> = ({
   innerRef, validationSchema,
}) => {
  const {
    values, errors, touched, setFieldValue,
  } = useFormikContext<RelationFormType>();

  return (
    <FormikStep>
      <Row>
          <DatePicker
            selected={values.institutional_relation_approval ? Date.parse(values.institutional_relation_approval) : ''}
            placeholderText="DD/MM/YYYY"
            dateFormat="dd/MM/yyyy"
            name="institutional_relation_approval"
            disabled={isView}
            onChange={((date) => {
              setFieldValue('institutional_relation_approval', date);
              console.log(date);
            })}
          />
    </FormikStep>
  );
};

export default RelationTypeStep;

以及我得到的错误:

No overload matches this call.
  Overload 1 of 2, '(props: ReactDatePickerProps | Readonly<ReactDatePickerProps>): ReactDatePicker', gave the following error.
    Type 'string | number' is not assignable to type 'Date | null | undefined'.
      Type 'string' is not assignable to type 'Date | null | undefined'.
  Overload 2 of 2, '(props: ReactDatePickerProps, context: any): ReactDatePicker', gave the following error.
    Type 'string | number' is not assignable to type 'Date | null | undefined'.  TS2769

我是否正确地注释了这种类型?这个无过载错误是什么意思?

1 个答案:

答案 0 :(得分:1)

不确定哪一行提示错误。

据我所知,选定的属性应该只接受 Datenull Date.parse() 返回数字而不是 Date,else 情况返回空字符串而不是 null,因此类型不兼容。

selected={
    values.institutional_relation_approval
    ? new Date(values.institutional_relation_approval) // return Date object
    : null // return null if no value provided
}