Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/denismurphy/emulating-associated-value-enums-typescript

Emulating Associated Value Enums in TypeScript
https://github.com/denismurphy/emulating-associated-value-enums-typescript

associated-values chai educational interface mocha npm swift types typescript union

Last synced: 2 months ago
JSON representation

Emulating Associated Value Enums in TypeScript

Awesome Lists containing this project

README

        

# ๐Ÿท๏ธ Emulating Associated Value Enums in TypeScript

This project demonstrates how to emulate Swift's Associated Value Enums in TypeScript.

๐Ÿ Swift allows defining Associated Value Enums that can contain other types within them. While TypeScript doesn't support this natively, it can be emulated using Interfaces and Type Unions.

## ๐Ÿ’ป Code Example

The code example creates a `Barcode` object with two methods:

- ๐Ÿ“Š `upc`: Creates a new barcode object with UPC values
- ๐Ÿ“ฑ `qrCode`: Creates a new barcode object with QR code values

It also includes two utility methods:

- โœ… `isUPC`: Checks if a given barcode is a UPC
- โœ… `isQRCode`: Checks if a given barcode is a QR code

The `switch` method returns a new `BarcodeSwitchBuilder` object that allows you to build a switch statement based on the barcode type.

## ๐Ÿงช Running the Tests

This project includes a Mocha test to ensure that the `BarcodeSwitchBuilder` works as expected.

To run the tests, execute the following command in your terminal:

```
npm test
```

## ๐ŸŽ“ Conclusion

Emulating Associated Value Enums in TypeScript can be achieved using Interfaces and Type Unions. The example provided in this project demonstrates one approach to accomplish this.