打字稿:返回号未定义

时间:2019-12-27 13:19:27

标签: angular typescript

我读出了一个json文件,其中包含方法和合计中的数据和战后信息,我想获取总成本。但是当我要计算product.price时返回未定义。因此,结果将显示为非数字。

{
    "id": "010",
    "productName": "Olivenöl",
    "specialOffer": 14.35,
    "normalPrice": 17.95,
    "imageName": "olivenoel.jpg",
    "description": "Bertolli Olivenöl extra vergine originale",
    "amount": 1
}

get total() {
    let sum: number = 0.0;
    this.products.forEach(product => { 
        console.log(product.price);
        sum += (product.price * product.amount)});
    console.log(sum)
    return sum;
}

export class Product {
id: string;
productName: string;
specialOffer?: number;
normalPrice: number;
imageName: string;
description: string;
amount: number;

get price(): number {
    if(this.hasSpecialOffer) {
        return this.specialOffer;
    } else {
        return this.normalPrice
    }
}

get hasSpecialOffer(): boolean {
    if(this.specialOffer) {
        return true
    } else {
        return false;
    }
}}

2 个答案:

答案 0 :(得分:1)

有空的时候

this.specialOffer?: number;

this.specialOffer的类型为undefined | number,不能分配给number。但是,您可以这样重写类型防护:

get price(): number {
  if(this.specialOffer != undefined) {
    return this.specialOffer;
  } else {
    return this.normalPrice
  }
}

顺便说一下,本文不需要hasSpecialOffer

TS可以毫无问题地进行编译,see for yourself

答案 1 :(得分:0)

我假设您是从某些外部资源或服务获取此JSON数据的。

因此,您将必须以以下方式在此处使用构造函数-

function checkConditions($product, $condition){
    if($condition['attribute'] !== false and $condition['operator'] !== false)
    {
        // simple condition 
        $variableToCheck = $product[ $condition['attribute'] ] ; // maybe use your API to query this value
        $operator = $condition['operator'] ;
        $valueToCompare = $condition['value'] ;
        return compareValue($variableToCheck, $operator, $valueToCompare);
    }
    else
    {
        // composite condition 
        if( $condition['aggregator'] == 'all' )
        {
            // check for each child condition
            foreach($condition['conditions'] as $childCondition)
            {
                $childConditionReturn = checkConditions($product, $childCondition);
                if($childConditionReturn === false)
                {
                    // we found a child condition that is not satisfied, the whole 'all' aggregator is false
                    return false ;
                }
            }

            // all childs were evaluated to true, whole 'all' aggregator is true
            return true ;
        }
        else // handle other aggregator types here
        {

        }
    }
}

您也可以使用loadash来使用上面的_.assign。

您可以像这样传递json数据-

constructor(data: Product) {
   id: data.id;
   productName: data.productName;
   specialOffer: data.specialOffer;
   normalPrice: data.normalPrice;
   imageName: data.imageName;
   description: data.description
 }

然后const data = new Product(json); 会给您带来我猜得到的结果。