1

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.

3
  • 1
    What Swift and Java refer to as an enum, other languages (including TypeScript) refer to as "discriminated-unions". Commented Oct 16, 2021 at 23:19
  • Which UPC specification are you using, btw? There isn't necessarily 4 modules in a UPC, so you should be specific about which spec you're using (e.g. UPC-A) Commented Oct 16, 2021 at 23:22
  • Ahhh yep that's what im looking for. Haha not doing anything with barcodes just found that example online. Thanks though!! Commented Oct 16, 2021 at 23:24

1 Answer 1

3

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.
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.