【问题标题】:How to resolve - Argument of type is not assignable to type - TYPESCRIPT如何解决 - 类型参数不可分配给类型 - TYPESCRIPT
【发布时间】:2022-06-24 15:14:45
【问题描述】:

我有一个函数,其中包含一个函数对象:

type ForMembers<S> = {
 [Key: string]: (arg: S) => void;
};

export default function transform<S extends { [index: string]: any }, D extends { [index: string]: any }>(
  source: S,
  interfaceName: string,
  forMembers?: ForMembers<S>
): D {
  const newObj = extract(source, getKeys(interfaceName));
  if (forMembers) {
    Object.keys(forMembers).forEach((key) => forMembers[key](newObj));
  }
  return newObj as unknown as D;
}

我的想法是我可以传递我想要的任何函数对象,但打字稿出于某种原因要求我传递 type 上存在的所有属性,否则会引发错误

例如,如果 D 是

interface Destination {
name: string;
bio: string;
names: string[];
profession: {
  field: string;
  level: string;
  };

我将函数称为:

transform<Source, Destination>(sourceData, "Destination", {
  name: () => {},
  bio: () => {},
  profession: () => {},
});
}

会报错:

类型参数 '{ name: () => void;生物:()=>无效;职业:() => 无效; }' 不可分配给“ForMembers”类型的参数。 类型 '{ name: () => void; 中缺少属性 'names'生物:()=>无效;职业:() => 无效; }' 但在 'ForMembers' 类型中是必需的。

如果我添加缺少的属性 - “名称”,错误就会消失,但是我只想传递我需要的属性,而不是全部。所以问题是这样的 - 如何让函数将 D 的任何属性组合作为成员,而不是全部?

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    你可以告诉 TS 一个对象的所有属性都是可选的,使用Partial

    forMembers?: Partial<ForMembers<S>>
    

    【讨论】:

      猜你喜欢
      • 2021-10-17
      • 2020-03-26
      • 2023-01-18
      • 1970-01-01
      • 2019-01-03
      • 2013-11-03
      • 2021-10-18
      • 2019-09-23
      • 2020-12-23
      相关资源
      最近更新 更多