【问题标题】:Unable to make typescript recognize typing无法使打字稿识别打字
【发布时间】:2023-03-26 01:47:01
【问题描述】:

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

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

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

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

我是否正确注释了这种类型?这个没有重载错误是什么意思?

【问题讨论】:

    标签: typescript types react-datepicker


    【解决方案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
    }
    

    【讨论】:

    • 就是这一行:selected={values.institutional_relation_approval ? Date.parse(values.institutional_relation_approval) : ''} ,正是您在回答中给我的那个,请原谅我没有说清楚。我会试试你的建议
    • 成功了!非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2020-04-30
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多