Material-UI - TypeScript - 通用自动完成

Dus*_*y48 9 typescript reactjs material-ui typescript-generics

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

但是,该道具getOptionLabel显示以下错误:

输入 '(选项: T) => T[keyof T] | “”' 不可分配给类型 '(option: T) => string'。

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

问题:为什么根据以下代码会发生此错误,我该如何解决?

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

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

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>
  );
}
Run Code Online (Sandbox Code Playgroud)

提前致谢!

小智 4

我得到了你的代码

getOptionLabel={(option) =>{
    const val = option[selectValue];
    return isString(val) ? val : ""
  }
Run Code Online (Sandbox Code Playgroud)

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