typescript - 带参数打字稿的枚举
问题描述
斯威夫特可以做到这一点:
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
有没有办法在 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
您还需要编写一个类型保护函数:
- https://www.typescriptlang.org/docs/handbook/advanced-types.html
- https://www.typescriptlang.org/docs/handbook/2/narrowing.html
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.
}
}
推荐阅读
- mysql - mySQL 添加条件内 case 子句
- c - 我目前在 Eclipse MacOS Big Sur 上进行 GDB 调试时遇到错误
- javascript - 如何在一段时间后自动隐藏“您已订阅我们的时事通讯”的消息?
- google-apps-script - 如何测试私人 Google 表格添加
- php - XAMPP 目前是否在 2021 年支持 Curl?
- java - LinkedList 与 ArrayList 的时间性能
- python - 如何使用 scikit-image 和/或 PIL 将 ProPhoto RGB 颜色空间转换为 RGB?
- excel - 找到第一个最低值
- sql - 查询时在PostgreSQL中将小数位向右移动
- javascript - 按比例缩放 Img 以填充没有 CSS 覆盖的整个容器 (javascript/React)