简体   繁体   English

将 object 和数组作为多播类型传递到 Angular 2 的 function 参数的问题(打字稿问题)

[英]Issue passing an object and array as a multi-cast type into a function argument for Angular 2 (Typescript Question)

My problem is very simple.我的问题很简单。 I want to pass an object (of Class CircuitBreaker) into my arguments.我想将 object(Class 断路器)传递到我的 arguments 中。 I want it to be reusable, however, so I would like to also use |但是,我希望它可以重复使用,所以我也想使用| to pass an array of this same Class as well.传递同样的 Class 的数组。

This creates syntax errors where the compiler is confused on accepting array functions (such as.some)这会导致编译器在接受数组函数(例如.some)时感到困惑时产生语法错误

Property 'some' does not exist on type 'CircuitBreakerThresholdBreakdown | 'CircuitBreakerThresholdBreakdown | 类型不存在属性'some' CircuitBreakerThresholdBreakdown[] CircuitBreakerThresholdBreakdown[]

and/or a property of a potential object:和/或潜在 object 的属性:

Property 'threshold' does not exist on type 'CircuitBreakerThresholdBreakdown | 'CircuitBreakerThresholdBreakdown | 类型不存在属性'阈值' CircuitBreakerThresholdBreakdown[] CircuitBreakerThresholdBreakdown[]

What am I missing here?我在这里想念什么?

public thresholdFunction(cBreakdowns: CircuitBreaker | CircuitBreaker[]): boolean {
    if (cBreakdowns.length > 1) {
        return cBreakdowns.some(singleBreakdown => {
            return singleBreakdown.breakdown.count > singleBreakdown.threshold.maximum ||
            singleBreakdown.breakdown.count < singleBreakdown.threshold.minimum;
        });
    } else {
        return cBreakdowns.breakdown.count < cBreakdowns.threshold.minimum;
    }
}

Modify your if statement this way:以这种方式修改您的if语句:

if (cBreakdowns instanceof Array) {
 // ...
} else {
 // ...
}

You can use spread operator in paramter (...) .您可以在参数(...)中使用扩展运算符。

  • When calling the function if you want to pass object then use thresholdFunction(obj);当调用 function 时,如果你想通过object然后使用thresholdFunction(obj); . .
  • If you want to pass array use thresholdFunction(...array);如果要传递array ,请使用thresholdFunction(...array); . . And update your code like below.并更新您的代码,如下所示。
  • You can also pass multiple objects with thresholdFunction(obj1, obj2, obj3);您还可以使用thresholdFunction(obj1, obj2, obj3);传递多个objects

public thresholdFunction(...cBreakdowns: CircuitBreaker[]): boolean {
    return cBreakdowns.some(singleBreakdown => {
        return singleBreakdown.breakdown.count > singleBreakdown.threshold.maximum ||
            singleBreakdown.breakdown.count < singleBreakdown.threshold.minimum;
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM