如何解决无法让打字稿识别打字
我正在处理这个项目,我们需要将所有从 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
我是否正确地注释了这种类型?这个无过载错误是什么意思?
解决方法
不确定哪一行提示错误。
据我所知,选定的属性应该只接受 Date
或 null
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
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。