Swift can do this:
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
Is there a way to include arguments in enum cases like that in Typescript? Thanks.
What Swift and Java refer to as an enum, other languages (including TypeScript) refer to as "union type".
TypeScript offers many ways to skin a cat, but one idiomatic implementation in TypeScript equivalent is:
type Upc = { S: number, L: number, M: number, R: number, E: number };
type QRCode = { asText: string };
type Barcode = Upc | QRCode;
As TypeScript uses type-erasure there isn't any runtime information that immediately self-describes a Barcode object as either a Upc or a QRCode, so in order to discriminate between Upc and QRCode you'll need to write a type-guard function too:
function isUpc( obj: Barcode ): obj is Upc {
const whatIf = obj as Upc;
return (
typeof whatIf.S === 'number' &&
typeof whatIf.L === 'number' &&
typeof whatIf.M === 'number' &&
typeof whatIf.R === 'number' &&
typeof whatIf.E === 'number'
);
}
function isQRCode( obj: Barcode ): obj is QRCode {
const whatIf = obj as QRCode;
return typeof whatIf.asText === 'string';
}
Used like so:
async function participateInGlobalTrade() {
const barcode: Barcode = await readFromBarcodeScanner();
if( isUpc( barcode ) ) {
console.log( "UPC: " + barcode.S ); // <-- Using `.S` is okay here because TypeScript *knows* `barcode` is a `Upc` object.
}
else if( isQRCode( barcode ) ) {
console.log( "QR Code: " + barcode.asText ); // <-- Using `.asText` is okay here because TypeScript *knows* `barcode` is a `QRCode` object.
}
}
enum, other languages (including TypeScript) refer to as "discriminated-unions".