enums-with-associated-values
v1.0.0
Published
Enums for typescript with associated values like it made in Swift
Readme
TypeScript Enum with Associated Values
A TypeScript implementation that mimics Swift's enum with associated values pattern, providing type-safe enumerated types that can carry additional data.
Features
- 🔒 Type-safe enum implementations
- 📦 Associated value support
- 🔍 Pattern matching
- ⚡️ Exhaustive switch statements
- 🛡️ Type guards
- 📝 Namespace organization
Installation
npm install typescriptUsage
type EnumValue<T, V> = { type: T; value: V };
function createEnumValue<T, V>(type: T, value: V): EnumValue<T, V> {
return { type, value };
}Example Implementations
Result Type
namespace Result {
export type Success = EnumValue<'success', string>;
export type Failure = EnumValue<'failure', Error>;
export type Result = Success | Failure;
export const success = (message: string): Success => createEnumValue('success', message);
export const failure = (error: Error): Failure => createEnumValue('failure', error);
}
// Usage
const result = Result.success("Operation completed");Network Response
namespace NetworkResponse {
export type Data = EnumValue<'data', { content: any; timestamp: number }>;
export type Error = EnumValue<'error', { code: number; message: string }>;
export type Loading = EnumValue<'loading', number>;
export type Offline = EnumValue<'offline', undefined>;
export type NetworkResponse = Data | Error | Loading | Offline;
// Factory functions
export const data = (content: any): Data =>
createEnumValue('data', { content, timestamp: Date.now() });
export const error = (code: number, message: string): Error =>
createEnumValue('error', { code, message });
}Payment method
namespace PaymentMethod {
export type CreditCard = EnumValue<'creditCard', {
number: string;
expiry: string;
cvv: string;
}>;
export type PayPal = EnumValue<'paypal', {
email: string;
}>;
// More payment types...
export type PaymentMethod = CreditCard | PayPal | /* other types */;
}Pattern matching
function handleNetworkResponse(response: NetworkResponse.NetworkResponse): string {
switch (response.type) {
case 'data':
return `Received data: ${JSON.stringify(response.value.content)}`;
case 'error':
return `Error ${response.value.code}: ${response.value.message}`;
case 'loading':
return `Loading: ${response.value}%`;
case 'offline':
return 'Device is offline';
}
}Type Guards
function isSuccess(result: Result.Result): result is Result.Success {
return result.type === 'success';
}Advanced Usage
Processing Payments
function processPayment(method: PaymentMethod.PaymentMethod, amount: number): string {
switch (method.type) {
case 'creditCard':
return `Processing $${amount} with credit card ending in ${method.value.number.slice(-4)}`;
case 'paypal':
return `Processing $${amount} with PayPal account ${method.value.email}`;
// Handle other payment methods...
}
}
// Usage
const payment = PaymentMethod.creditCard('4111111111111111', '12/24', '123');
console.log(processPayment(payment, 100));License
This project is licensed under the MIT License - see the LICENSE file for details
Author
Siarhei Ladzeika [email protected]
