@praha/tagged
v1.0.0
Published
Lightweight TypeScript tagged union (discriminated union) utilities.
Readme
@praha/tagged
Lightweight TypeScript tagged union (discriminated union) utilities.
👏 Getting Started
Installation
npm install @praha/taggedUsage
Basic Usage
Define a tagged type using the Tagged factory:
import { Tagged } from '@praha/tagged';
const User = Tagged({
tag: 'User',
fields: Tagged.fields<{ name: string; age: number }>(),
});
const user = User({ name: 'Alice', age: 30 });
// => { $tag: 'User', name: 'Alice', age: 30 }Tag-Only (No Fields)
const Loading = Tagged({ tag: 'Loading' });
const loading = Loading();
// => { $tag: 'Loading' }Discriminated Union
Combine multiple tagged types into a union for exhaustive type narrowing:
import { Tagged } from '@praha/tagged';
const Success = Tagged({
tag: 'Success',
fields: Tagged.fields<{ data: string }>(),
});
const Failure = Tagged({
tag: 'Failure',
fields: Tagged.fields<{ message: string }>(),
});
const Loading = Tagged({
tag: 'Loading',
});
type Result = (
| typeof Success.$infer
| typeof Failure.$infer
| typeof Loading.$infer
);
const handle = (result: Result) => {
switch (result.$tag) {
case 'Success':
console.log(result.data);
break;
case 'Failure':
console.error(result.message);
break;
case 'Loading':
console.log('Loading...');
break;
}
};Inferring Types
Use $infer to extract the TypeScript type from a factory:
type User = typeof User.$infer;
// => { $tag: 'User'; name: string; age: number }🤝 Contributing
Contributions, issues and feature requests are welcome.
Feel free to check issues page if you want to contribute.
📝 License
Copyright © PrAha, Inc.
This project is MIT licensed.
