opaque-types
Support for opaque and nominal types in typescript via a transformation.
Installation
yarn add opaque-types
Usage
Define a file with the extension .src.ts
. e.g. types.src.ts
// @nominal;// @nominal; // @opaque; // @nominal// @expose;;
Running opaque-types <dirname>
will generate a file called types.ts
(i.e. without the .src
part), that exposes opaque/nominal types, along with an API for casting to and from them.
Usage:
; ;;; goi, x, y;// errors: go(i, y, x); // errors: const a: number = x;// errors: const b: number = y;;; // cast validates the value. It is only// available if `isValid` is defined.;;// errors: const e: Email = 'forbes@example.com';sendMessageemail, 'Hi person at ' + email;
@nominal
marks the type as a "nominal" type. If you declare the same "nominal" type, with the same name, in multiple different files, they will be treated as the same type. This is useful if you want to create a library that exposes an API with types like "Email".@opaque
marks the type as an "opaque" type. Each declaration of an@opaque
type is separate, and cannot be confused, even if they have the same name.@expose
exposes the underlying type. In the above example, you can use anEmail
in a location where astring
is required, but you still cannot pass an arbitrary string to a method expecting anEmail
.
License
MIT