Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/joshuajaco/ts-nominal
Nominal typing in TypeScript
https://github.com/joshuajaco/ts-nominal
nominal nominal-types nominal-typing typescript
Last synced: 26 days ago
JSON representation
Nominal typing in TypeScript
- Host: GitHub
- URL: https://github.com/joshuajaco/ts-nominal
- Owner: joshuajaco
- License: mit
- Created: 2022-12-22T23:44:41.000Z (almost 2 years ago)
- Default Branch: main
- Last Pushed: 2023-03-04T19:53:08.000Z (over 1 year ago)
- Last Synced: 2024-09-16T07:18:52.563Z (about 2 months ago)
- Topics: nominal, nominal-types, nominal-typing, typescript
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/ts-nominal
- Size: 19.5 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# ts-nominal
Nominal typing in TypeScript.
## Installation
```sh
# npm
npm install ts-nominal# yarn
yarn add ts-nominal# pnpm
pnpm install ts-nominal
```## Usage
### `Nominal`
Create a nominal type from any type `T` using the unique symbol `U`.
#### Example
```ts
import type { Nominal } from "ts-nominal";declare const __FOO_STRING_ID: unique symbol;
type FooString = Nominal;declare let foo: FooString;
declare let fooLike: string;// 'FooString' can be assigned to type 'string'
fooLike = foo;// 'string' cannot be assigned to type 'FooString'
foo = fooLike; // Error: Type 'string' is not assignable to type 'FooString'.// casting still works
foo = fooLike as FooString;
```### `nominal(value)`
Cast `value` to the nominal type `T`. Equivalent to `value as T`, but with autocompletion for `value`.
It does not modify `value` in any way and has essentially no overhead on the resulting JavaScript (transpiles to `(value) => value`).#### Example
```ts
import { type Nominal, nominal } from "ts-nominal";declare const __FOO_STRING_ID: unique symbol;
type FooString = Nominal;const foo: FooString = nominal("foo");
// create a factory by only providing the type argument
const createFoo = nominal;
const foo2 = createFoo("foo2");// comparisons still function as usual
foo === "foo"; // true
foo === "bar"; // false
```## License
[MIT](https://github.com/joshuajaco/ts-nominal/blob/main/LICENSE)