从 js 转换到 ts 时出现打字稿错误

时间:2021-04-06 18:44:57

标签: reactjs typescript

我正在尝试将 js 转换为 ts,但出现以下错误

类型 '(props: PropsWithChildren) => (any[] | ((e: any) => void))[]' 不能分配给类型 'FC'。 类型 '(any[] | ((e: any) => void))[]' 缺少来自类型 'ReactElement' 的以下属性:type, props, keyts(2322)< /p>

这是JS代码

    import { useState } from "react";
export const useForm = initialValues => {
  const [values, setValues] = useState(initialValues);
  return [
    values,
    e => {
      setValues({
        ...values,
        [e.target.name]: e.target.value
      });
    }
  ];
};

这是我的 ts 代码

    import React, { useState } from "react";
export interface Props {
  initialValues: any[];
}
const useForm: React.FC<Props> = (props) => {
  const [values, setValues] = useState(props.initialValues);
  return [
    values,
    (e: any) => {
      setValues({
        ...values,
        [e.target.name]: e.target.value,
      });
    },
  ];
};
export default useForm;

enter image description here

任何帮助都会得到满足

1 个答案:

答案 0 :(得分:1)

你已经创建了一个新的钩子 useForm,它不是一个功能组件,所以你不能将它的类型声明为 React.FC,你需要定义它的参数和返回类型。 就像这样:

const useForm = (initialValues: any[]): [any[], (value: any) => void] => {
    ...useForm function content
}

你当然可以在外面提取函数的类型,像这样:

type UseForm = (initialValues: any[]) => [any[], (value: any) => void];
const useForm: UseForm => {
    ...useForm function content
}