Accept unknown and safely work toward a number. If the input is an array of objects with a numeric price, sum the prices. Otherwise return 0.
Check with Array.isArray. Then, for each item, make sure it is an object, not null, has a price key, and that price is a number.
function total(xs: unknown) {
if (!Array.isArray(xs)) return 0;
let t = 0;
for (const it of xs) {
if (typeof it === "object" && it && "price" in it) {
const p = (it as { price?: unknown }).price;
if (typeof p === "number") t += p;
}
}
return t;
}
Implement a function that totals prices when input is an array of price objects.