使用泛型将函数类型分配给变量

问题描述 投票:0回答:1

我有一个已经声明的带有泛型的函数类型,我想将其分配给一个命名的箭头函数。这是一个代码示例:

import { AutocompleteProps } from '@material-ui/lab/Autocomplete';

const itemToString: AutocompleteProps<
  T,
  Multiple,
  DisableClearable,
  FreeSolo
>['getOptionLabel'] = (i) =>
  (typeof i === 'string' ? i : (i?.name as string)) || '';

但是打字稿警告我它找不到

T, Multiple, DisableClearable, FreeSolo
泛型。

您能告诉我应该在哪里定义它们吗?

编辑:我希望将此函数传递给

getOptionLabel
组件调用的
Autocomplete
属性并继承他的泛型(如果我措辞不正确,再次抱歉)。这是可能的还是我应该接受 Rajiv 的回答

Edit2:像这样的东西(这与我想要做的非常接近)也不起作用

const itemToString: <
  T extends Entity,
  Multiple extends boolean,
  DisableClearable extends boolean,
  FreeSolo extends boolean
> AutocompleteProps<
  T,
  Multiple,
  DisableClearable,
  FreeSolo
>['getOptionLabel'] = (i) => (typeof i === 'string' ? i : (i?.name as string)) || '';
javascript typescript material-ui autocomplete
1个回答
2
投票

所以这里所有的参数都需要一些值

T
:选项对象的形状。
Multiple
:布尔值,是否对多个值使用自动完成功能。
DisableClearable
:布尔值是否可以清除输入。
FreeSolo
:布尔值,用于决定用户输入是否不绑定到提供的选项。

因此,根据您的要求,您可以提供价值。我添加了一个用于演示的示例界面。

import { AutocompleteProps } from '@material-ui/lab/Autocomplete';

interface IOption {
  label: string,
  value: string,
}

const itemToString: AutocompleteProps<
  IOption,
  false,
  false,
  false
>['getOptionLabel'] = (i) =>
  (typeof i === 'string' ? i : (i?.name as string)) || '';

© www.soinside.com 2019 - 2024. All rights reserved.