typescript 错误:reactjs中的类型“unknown”. ts(2339)上不存在属性“label”

toe95027  于 2023-01-14  发布在  TypeScript
关注(0)|答案(1)|浏览(314)

我下面的链接创建一个简单的例子
https://github.com/adiathasan/mui-react-hook-form-plus
或实时示例
https://mui-react-hook-form-plus.vercel.app/?path=/docs/form-context--hookformprovider
但在拆分代码时,我收到此错误类型“unknown”上不存在属性“label”。ts(2339)
当我把所有的代码在同一个文件中,它是工作正常

运行良好的演示

https://codesandbox.io/s/xenodochial-flower-0r3hdf?file=/src/App.tsx
但是当我把组件分开时,我得到了上述错误

无法正常工作https://codesandbox.io/s/mystifying-sky-6b2gs8?file=/src/autpcomplete.tsx:732-744

export default function AutoComplete({ registerState }) {
  return (
    <HookAutoComplete
      {...registerState("movie")}
      autocompleteProps={{
        options: top100Films,
        autoHighlight: true,
        isOptionEqualToValue: ({ label }, value) => label === value.label
      }}
      textFieldProps={{
        label: "Movie",
        placeholder: "The..."
      }}
      gridProps={{
        xs: 12
      }}
      rules={{
        required: {
          message: "Required",
          value: true
        }
      }}
    />
  );
}

9q78igpj

9q78igpj1#

在“工作”版本中,似乎所有类型都允许被推断,因为所有的东西都是组件内部的。当你创建一个外部组件时,你没有输入传递给你的AutoComplete组件的props。理想情况下,你应该完全输入HookAutoComplete props对象。
不必深入了解mui-react-hook-form-plus是如何从react-hook-form导出钩子和任何类型声明的,只需手动键入isOptionEqualToValue就可以了。

interface FilmOption {
  label: string;
  year: number;
}

interface Value {
  label: string;
}

export const top100Films: FilmOption[] = [
  { label: "The Shawshank Redemption", year: 1994 },
  { label: "The Godfather", year: 1972 },
  { label: "The Godfather: Part II", year: 1974 },
  { label: "The Dark Knight", year: 2008 },
  { label: "12 Angry Men", year: 1957 },
  { label: "Schindler's List", year: 1993 },
  { label: "Pulp Fiction", year: 1994 }
];

export default function AutoComplete({ registerState }) {
  return (
    <HookAutoComplete
      {...registerState("movie")}
      autocompleteProps={{
        options: top100Films,
        autoHighlight: true,
        isOptionEqualToValue: ({ label }: FilmOption, value: Value) =>
          label === value.label
      }}
      textFieldProps={{
        label: "Movie",
        placeholder: "The..."
      }}
      gridProps={{
        xs: 12
      }}
      rules={{
        required: {
          message: "Required",
          value: true
        }
      }}
    />
  );
}

相关问题