Reputation: 66
Getting the following error:
expression of type
?Product/798
cannot produce expected type
{id : Nat; name : Text; price : Nat; sku : Text}
when trying to loop over a list of ids, get the corresponding HashMap value, and add to a new array only if the get() function returns a Product.
for (id in productIds.vals()) {
var product: ?Product = products.products.get(id);
if (product != null) {
products_list := Array.append<Product>(products_list, [product]);
};
};
Am I maybe misunderstanding the best way to approach this? It seems like I shouldn't get any errors because if it's not a Product type (which is the "expected type" it references) it should just continue on, right?
Upvotes: 0
Views: 704
Reputation: 36098
The variable product
is of type ?Product
, but your instantiation of the Array.append
function expects an array of values of plain type Product
.
The comparison with null
does not magically change the type of the variable. You'll need to pattern-match it with a switch
to extract the actual value:
switch product {
case (?p) { products_list := Array.append<Product>(products_list, [p]) };
case null { ...do something else... };
}
Upvotes: 1