The product object to validate
Array of missing or invalid field names (empty if all fields are valid)
TypeError if product is null or not an object
const product = { title: "NaCl", price: 29.99, quantity: 500, uom: "g" };
const missing = checkCompleteProductFields(product);
// ["supplier", "url", "currencyCode", "currencySymbol"]
export function checkCompleteProductFields(product: unknown): string[] {
if (!product || typeof product !== "object") {
throw new TypeError("checkCompleteProductFields| Invalid product", { cause: product });
}
const requiredProps: Record<keyof RequiredProductFields, string> = {
title: "string",
price: "number",
quantity: "number",
uom: "string",
supplier: "string",
url: "string",
currencyCode: "string",
currencySymbol: "string",
};
const record = product as Record<string, unknown>;
const result = Object.entries(requiredProps).reduce(
(acc: string[], [key, expectedType]: [string, string]) => {
if (key in record === false) {
console.debug("checkCompleteProductFields| No value found in product", { product, key });
return [...acc, key];
}
if (typeof record[key] !== expectedType) {
console.debug("checkCompleteProductFields| Property not the correct type", {
product,
key,
expectedType,
actualType: typeof record[key],
});
return [...acc, key];
}
return acc;
},
[],
);
if (result.length > 0) {
console.warn("checkCompleteProductFields| Results for product is", { product, result });
}
return result;
}
Checks a product object for missing or incorrectly typed complete required fields. Returns an array of field names that are missing or have the wrong type.