【问题标题】:Reduce error type param pipe transform Angular [closed]减少错误类型参数管道变换Angular [关闭]
【发布时间】:2021-06-23 04:24:50
【问题描述】:

我创建了一个转换管道来减少对象列表

export class SumPipe implements PipeTransform {
  transform(items: ListCount[], attr: string): number {
    return items.reduce((a, b) => a + b[attr], 0);
  }
}

这是 ListCount 的模型:

export interface ListCount {
  centre?: string;
  cause?: string;
  Time?: number;
}

但我有这个错误:

 error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ListCount'

请帮忙

【问题讨论】:

  • 为什么这被关闭为拼写错误/不可重现?如果它是重复的,我不会感到惊讶,但除此之外,这是一个完全有效的问题。

标签: angular typescript pipe reduce


【解决方案1】:

正如HTN answer 中提到的那样,使用attr: keyof ListCount 收紧attr 参数的类型,但因为ListCount 同时具有stringnumber 值属性,您需要验证您获取的属性是否来自bnumber 类型,使用 typeof

export class SumPipe implements PipeTransform {
  transform(items: ListCount[], attr: keyof ListCount): number {
    return items.reduce((a, b) => {
      // get `attr` value from `b`
      const value = b[attr];
      // validate if type of `b[attr]` is number
      // - if so do the addition
      // - otherwise return previous `a` value
      return typeof value === 'number' ? a += value : a;
    }, 0);
  }
}

【讨论】:

    【解决方案2】:

    因为attr是一个字符串,所以不是ListCount的已知属性

    你可以试试:

    export class SumPipe implements PipeTransform {
      transform(items: ListCount[], attr: keyof ListCount): number {
        return items.reduce((a, b) => a + b[attr], 0);
      }
    }
    

    【讨论】:

    • 我有这个错误:error TS2365: Operator '+' cannot be applied to types 'number' and 'string | number'. error TS2532: Object is possibly 'undefined'.
    • 这是 ListCount 的模型:export interface ListCount { centre?: string; cause?: string; Time?: number; }
    • 如果只想添加time,为什么还要使用attr?只需:return items.reduce((a, b) => a + b.Time, 0);。但是,不要忘记 Time 也可以是未定义的,在这种情况下你会做什么,让它像 0 ? return items.reduce((a, b) => a + (b.Time ?? 0), 0);
    猜你喜欢
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    • 2012-02-23
    • 1970-01-01
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多