You can use a discriminated union for this. This example uses Typescript, but the concept would be similar for Javascript just without the type safety.
interface UPCA {
kind: "UPCA";
numberSystem: number;
manufacturer: number;
item: number;
checkDigit: number;
}
interface QRCode {
kind: "QRCode";
data: string;
}
interface Other {
kind: "Other";
}
type Barcode = UPCA | QRCode | Other;
You can then switch over a value of Barcode and access the associated values after checking the discriminate.
function printBarcode(barcode: Barcode) {
switch (barcode.kind) {
case "UPCA":
console.log(`UPCA: ${barcode.numberSystem}-${barcode.manufacturer}`);
break;
case "QRCode":
console.log(`QRCode: ${barcode.data}`);
break;
case "Other":
console.log("Other barcode");
break;
}
}