【问题标题】:Typescript complains about missing property that isn't missing打字稿抱怨缺少没有丢失的属性
【发布时间】:2018-03-16 05:59:36
【问题描述】:

我有一个简单的接口定义为:

export interface ISnapShot {
  val: () => any;
  key: string;
  forEach: (child: ISnapShot) => boolean;
}

然而,当我尝试在这里实现 forEach 方法时:

export function snapshotToOrderedArray<T = IDictionary>(
  snap: ISnapShot,
  idProp = 'id'
): T[] {
  const output: T[] = [];
  snap.forEach((child: ISnapShot) => {
    const obj: any = child.val();
    const key: string = child.key;
    if (typeof obj !== 'object' ) {
      throw new Error(`Can't create a list from scalar values: "${obj}" | "${key}"`);
    }

    output.push( { ...{[idProp]: key }, ...obj } );

    return true;
  });

  return output as T[];
}

我收到此错误:

[ts] '(child: ISnapShot) => boolean' 类型的参数不可分配给'ISnapShot' 类型的参数。 类型 '(child: ISnapShot) => boolean' 中缺少属性 'val'。

不确定如何处理此错误。 ISnapShot 接口明确声明有一个 val 属性。我做错了什么?

【问题讨论】:

  • 使用版本2.4.2

标签: typescript


【解决方案1】:

在接口ISnapShot中,方法forEach接受一个I​​SnapShot类型的参数并返回一个boolean。预期的电话是snap.forEach(childSnap)

如果你想要一个类似数组的forEach,参数必须是一个函数,例如(与ES6 method shorthands一起使用以获得更好的可读性)

interface ISnapShot {
  // [...]
  forEach(mapper: (child: ISnapShot) => boolean): void;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-01
    • 2021-09-23
    • 2018-10-14
    • 2020-01-06
    • 2021-04-29
    • 2013-09-17
    • 1970-01-01
    相关资源
    最近更新 更多