https://github.com/joshuajaco/ts-nominal
Nominal typing in TypeScript
https://github.com/joshuajaco/ts-nominal
nominal nominal-types nominal-typing typescript
Last synced: 8 months 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 (over 3 years ago)
- Default Branch: main
- Last Pushed: 2023-03-04T19:53:08.000Z (over 3 years ago)
- Last Synced: 2025-02-15T08:47:06.086Z (over 1 year 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)