【问题标题】:Material-UI - TypeScript - Generic AutocompleteMaterial-UI - TypeScript - 通用自动完成
【发布时间】:2020-12-14 15:26:32
【问题描述】:

使用 TypeScript,我正在尝试创建一个 Material-UI AutoComplete 组件,该组件根据对象属性名称获取输入值 -> obj[key]

但是,prop getOptionLabel 显示以下错误:

键入'(选项:T)=> T[keyof T] | ""' 不可分配给类型 '(选项:T)=> 字符串'。

prop 需要一个字符串,我知道对象属性的值可能不是字符串。

问题:为什么根据下面的代码会出现这个错误,我该如何解决?

代码框链接: https://codesandbox.io/s/mui-ts-generic-autocomplete-o0elk?fontsize=14&hidenavigation=1&theme=dark

还有原始代码,以防代码框链接在某些时候无法反映原始问题:

import * as React from "react";
import { Autocomplete } from "@material-ui/lab";
import { TextField } from "@material-ui/core";

export const isString = (item: any): item is string => {
  return typeof item === "string";
};

type AutoCompleteFieldProps<T> = {
  selectValue: keyof T;
  options: T[];
};

// Top films as rated by IMDb users. http://www.imdb.com/chart/top
const topFilms = [
  { title: "The Shawshank Redemption", year: 1994 },
  { title: "The Godfather", year: 1972 },
  { title: "The Godfather: Part II", year: 1974 },
  { title: "The Dark Knight", year: 2008 },
  { title: "12 Angry Men", year: 1957 },
  { title: "Schindler's List", year: 1993 },
  { title: "Pulp Fiction", year: 1994 }
];

const AutoCompleteField = <T extends {}>({
  selectValue,
  options
}: AutoCompleteFieldProps<T>): React.ReactElement => {
  return (
    <Autocomplete<T>
      id={name}
      options={options}
      fullWidth
      // Error here
      getOptionLabel={(option) =>
        isString(option[selectValue]) ? option[selectValue] : ""
      }
      renderInput={(params) => (
        <TextField {...params} label="demo autocomplete" />
      )}
    />
  );
};

// error:
// Type '(option: T) => T[keyof T] | ""' is not assignable to type '(option: T) => string'.

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <AutoCompleteField<{ title: string; year: number }>
        options={topFilms}
        selectValue="title"
      />
    </div>
  );
}

提前致谢!

【问题讨论】:

    标签: reactjs typescript material-ui typescript-generics


    【解决方案1】:

    我得到了你的代码

    getOptionLabel={(option) =>{
        const val = option[selectValue];
        return isString(val) ? val : ""
      }
    

    如果不直接使用变量,类型保护似乎无法正常工作。

    【讨论】:

    • 我觉得这个解决方案是对猎枪伤口的创可贴。我们可以简单地强制 selectedValue 是堆栈中更高的字符串,而不是在最后机会时满足它不是字符串的情况。必须有某种方式强制 selectedValue 是一个字符串,它是一个进入组件的道具,它是 keyof 类型 T。很抱歉负面评论,我只是想知道使用 TS 的意义是什么,如果我们只是为了让它转译而做这些小技巧
    • 检查值是否为字符串不是我的解决方案,而是海报的解决方案。我只是在修复打字稿错误。此外,在海报的情况下,如果 selectValue 为“year”,则 value option[selectValue] 将是一个数字。我试过你的链接,但它只显示与海报中的原始代码沙箱相同的代码,当我粘贴你的答案时,我仍然看到一个错误。我也不完全理解您的类型,因为您似乎在说 option[selectValue] 是 T 类型,但在海报的情况下,T 似乎是 topFilms 中的一个条目。
    • 太好了,这似乎比“任何”更合适。有趣的事实是,如果没有原始值,类型保护就无法工作。谢谢!
    【解决方案2】:

    使option 类型为any (option: any) 成功了

    getOptionLabel={(option: any) =>
      isString(option[selectValue]) ? option[selectValue] : ""
    }
    

    【讨论】:

    • 有趣。感谢您的回答。虽然这可行,但如果您或其他任何人能够详细说明为什么在这种情况下需要任何东西,我会很高兴。再次感谢
    猜你喜欢
    • 2022-01-04
    • 2020-08-13
    • 2023-03-24
    • 2020-07-30
    • 1970-01-01
    • 2021-09-06
    • 2021-10-04
    • 2020-09-18
    • 2020-05-04
    相关资源
    最近更新 更多