【问题标题】:react-material table with typescript shows generic type error带有打字稿的反应材料表显示通用类型错误
【发布时间】:2023-03-08 06:46:01
【问题描述】:

我正在尝试在 Typescript 项目下运行 react-material

由于我是 Typescript 的新手,我遇到了一些错误,我不知道如何解决它们。

在这个guest 中,我正在尝试创建一个可重用的 React 组件。 (请打开客人查看完整代码)

正如我所说,上面的示例显示了一些错误,这是 homePage 第 48 行中的示例:

No overload matches this call.
  Overload 1 of 2, '(props: Readonly<MaterialTableProps<IData>>): KTable<IData>', gave the following error.
    Type '{ title: string; field: string; type: string; }[]' is not assignable to type 'Column<IData>[]'.
      Type '{ title: string; field: string; type: string; }' is not assignable to type 'Column<IData>'.
        Types of property 'type' are incompatible.
          Type 'string' is not assignable to type '"string" | "boolean" | "time" | "numeric" | "date" | "datetime" | "currency" | undefined'.
  Overload 2 of 2, '(props: MaterialTableProps<IData>, context?: any): KTable<IData>', gave the following error.
    Type '{ title: string; field: string; type: string; }[]' is not assignable to type 'Column<IData>[]'.ts(2769)

为什么这个数组显示错误?

columns = [...{
    title: "Birth Place",
    field: "birthCity",
    type: "string" // ERROR ?!
}]

尽管接口明确定义了类型接受字符串:

type?: ('string' | 'boolean' | 'numeric' | 'date' | 'datetime' | 'time' | 'currency');

如果有人知道如何完成这项工作,将会很有帮助。

【问题讨论】:

    标签: reactjs typescript material-ui material-table


    【解决方案1】:

    使用原始字符串值string 将被解释为不是正确类型的字符串。 要解决这个问题,请将其转换为 const

    columns = [...{
        title: "Birth Place",
        field: "birthCity",
        type: "string" as const // ERROR ?!
    }]
    

    【讨论】:

      【解决方案2】:

      已解决!天哪,我花了这么多时间来处理这个打字稿错误......

      type IType =
        | "string"
        | "boolean"
        | "numeric"
        | "date"
        | "datetime"
        | "time"
        | "currency";
      const string: IType = "string";
      
      const columns = [
        {
          title: "Name",
          field: "name",
          type: string
        },
        {
          title: "Surname",
          field: "surname",
          type: string
        },
        {
          title: "Birth Year",
          field: "birthYear",
          type: string
        },
        {
          title: "Birth Place",
          field: "birthCity",
          // lookup: { 34: "İstanbul", 63: "Şanlıurfa", 1: "Berlin", 2: "Tunis" },
          type: string
        }
      ];
      

      【讨论】:

        【解决方案3】:

        string 实际上不是列类型可接受的类型:

        我创建了一个 PR 来解决这个问题,但如果你要显示一个字符串,你可以省略类型。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-12-20
          • 2017-01-12
          • 1970-01-01
          • 2021-08-30
          • 1970-01-01
          • 2017-10-30
          • 2019-05-10
          • 2021-09-23
          相关资源
          最近更新 更多