TS2322:无法将类型“ D [string]”分配给类型“ string”

时间:2020-10-10 15:31:23

标签: typescript typescript-generics

这是代码:

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" }

...以及值myLabelfilter函数将返回字符串“ 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'.

1 个答案:

答案 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的键(值是字符串)。