类型“ {}”的对象不存在属性“ condition”

时间:2019-10-10 13:02:19

标签: typescript

我在对象中添加键和值时遇到问题,但遇到错误,例如类型'{}'对象上不存在属性'condition'。

static deleteProductReview(request: Request) {
    let deleteParam  = { };
    deleteParam['condition']={'name': "ssssss"},
    deleteParam['params']={
        'reviews_ratings': {
            'regno': "468sdsdd")
        }
    };
    return deleteParam;
}

预期输出:

 {
        condition:{
            name: ssssss
        },
        params:{
            reviews_ratings:{
                regno:468sdsdd
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

一种选择是立即在Typescript推断对象类型的地方分配值

static deleteProductReview(request: Request) {
    let deleteParam = { 
      condition: { name : "ssssss" },
      params: {
        reviews_rating: {
          regno: "468sdsdd"
        }
      }
    };
    return deleteParam;
}

如果要在特定条件下动态添加属性,并且不想为deleteParam定义特定类型,则可以将其标记为any

static deleteDynamicProductReview(request: Request) {
    let deleteParam: any = { };
    deleteParam['condition']={'name': "ssssss"},
    deleteParam['params']={
        'reviews_ratings': {
            'regno': "468sdsdd")
        }
    };
    return deleteParam;
}

请注意,deleteDynamicProductReview返回的对象将不会自动完成,因为它的类型为any