这是代码:
export interface CreateFilterOptionsConfig < T > {
stringify ? : (option: T) => string;
}
interface AutoCompleteFieldProps < D extends object > {
options: Array < D > ;
labelKey: keyof D;
}
const AutoCompleteField = < D extends object > ({
options,
labelKey,
}: AutoCompleteFieldProps < D > ) => {
const filter = createFilterOptions < D > ({
stringify: (option) => option[labelKey]
});
return <div > < /div>
}
不用多说,为了简洁起见,对它进行了修剪。这个想法是,如果我向AutoCompleteField
提供了以下对象:
{ id: 0, myLabel: "some label" }
...以及值myLabel
,filter
函数将返回字符串“ some label”。只要我提供应该从中返回显示字符串的键字段,这就可以提供任意类型。
但是我得到了以下错误:
TS2322: Type '(option: D) => D[keyof D]' is not assignable to type '(option: D) => string'.
Type 'D[keyof D]' is not assignable to type 'string'.
Type 'D[string] | D[number] | D[symbol]' is not assignable to type 'string'.
Type 'D[string]' is not assignable to type 'string'.
答案 0 :(得分:2)
问题是您的对象D
既没有字符串,也没有labelKey
限于包含字符串的键。
如果您只想将D
限制为字符串,则应指出<D extends {[key: string]: string}>
。
如果您想限制labelKey
,则要复杂一些:
type StringPropertyNames<T> = {
[K in keyof T]: T[K] extends string ? K : never;
}[keyof T];
interface AutoCompleteFieldProps < D extends object > {
options: Array < D > ;
labelKey: StringPropertyNames<D>;
}
StringPropertyNames
类型仅采用T
的键(值是字符串)。