首页 > 解决方案 > 带参数打字稿的枚举

问题描述

斯威夫特可以做到这一点:

enum Barcode {
    case upc(Int, Int, Int, Int)
    case qrCode(String)
}

有没有办法在 Typescript 中的枚举案例中包含参数?谢谢。

标签: typescript

解决方案


Swift 和 Java 所指的是enum,其他语言(包括 TypeScript)则称为“联合类型”

TypeScript 提供了许多给猫换皮的方法,但 TypeScript 等效的一种惯用实现是:

type Upc     = { S: number, L: number, M: number, R: number, E: number };
type QRCode  = { asText: string };
type Barcode = Upc | QRCode;

由于 TypeScript 使用类型擦除,因此没有任何运行时信息可以立即Barcode将对象自我描述为 aUpc或 a QRCode,因此为了区分Upc并且QRCode您还需要编写一个类型保护函数:

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';
}

像这样使用:

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.
    }
}

推荐阅读