branded-types
Flippin' great branded types for TypeScript!
Use them like opaque types in Flow, except you get to control visibility.
Simple example
Define a branded type:
import {Branded} from 'branded-types'
export class OrderId extends Branded<string, 'my-package.OrderId'>() {}
Import and use it
import {OrderId} from './other-module';
OrderId.brand('someUuid') === 'someString'
Advanced example
Want to hide the branding and un-branding functions?
- Declare your branded type in namespace
- Use the static functions within your module to safely create instances
- Export only the type instead of the entire class
import { Branded } from "branded-types";
namespace my {
export class OrderId extends Branded<string, 'my-package.OrderId'>() {}
}
export function safeCreateId() {
return my.OrderId.brand('x')
}
export type OrderId = my.OrderId;
The other module can only use the safe ID creation functions now:
import {safeCreateId, OrderId} from './other-module';
safeCreateId() == 'someString';
let m: Map<OrderId, string> = new Map;
m.set(safeCreateId(), '1');
m.set('someString', '2');
Features