Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/ncpa0cpl/unique-enum-ts
https://github.com/ncpa0cpl/unique-enum-ts
Last synced: about 10 hours ago
JSON representation
- Host: GitHub
- URL: https://github.com/ncpa0cpl/unique-enum-ts
- Owner: ncpa0cpl
- License: mit
- Created: 2021-09-22T11:02:32.000Z (about 3 years ago)
- Default Branch: master
- Last Pushed: 2022-03-02T10:51:39.000Z (over 2 years ago)
- Last Synced: 2023-12-24T00:04:26.206Z (11 months ago)
- Language: TypeScript
- Size: 5.86 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Unique Enum TS
#### Utility for creating Enum-like objects with unique values
## Usage
Define the enum:
```ts
import { UniqueEnum } from "unique-enum-ts";const MyEnum = UniqueEnum({
FOO: "FOO",
BAR: "BAR",
} as const);// OR
// Use the TS enum syntax and assert the values uniqueness with the UniqueEnum functionenum MyEnum {
FOO = "FOO",
BAR = "BAR",
}UniqueEnum(MyEnum);
```If you don't use the TS enums syntax, you will need to extract the enum type like this:
```ts
type MyEnumValues = typeof MyEnum[keyof typeof MyEnum];function baz(myEnum: MyEnumValues) {
switch (myEnum) {
case MyEnum.FOO:
// do something when myEnum === 'foo'
break;
case MyEnum.BAR:
// do something when myEnum === 'bar'
break;
}
}
```## Enum Uniqueness
Unique Enum does not do a uniqueness check at runtime. It only provides Typescript type checking on the enum values.
This means that the following declaration will throw an compile error (since the value "foo" is used twice):
```ts
import { UniqueEnum } from "unique-enum-ts";const MyEnum = UniqueEnum({
FOO: "foo",
BAR: "bar",
ANOTHER_FOO: "foo",
} as const);
```However if the compilation error were to be ignored, this code will execute just fine, without any errors or warnings.