Skip to content

Commit

Permalink
fix: prevent assigning UUIDs to different versions
Browse files Browse the repository at this point in the history
This change stores the UUID version as a phantom type so that it's no longer possible to assign a
UUID version 1 to a UUID version 2, for example.
  • Loading branch information
thewilkybarkid committed Apr 5, 2022
1 parent 5f5940a commit 7f70616
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@
* @category model
* @since 0.1.0
*/
export type Uuid<V extends UuidVersion = UuidVersion> = string & UuidBrand
export type Uuid<V extends UuidVersion = UuidVersion> = string & UuidBrand<V>

type UuidVersion = 1 | 2 | 3 | 4 | 5

interface UuidBrand {
interface UuidBrand<V extends UuidVersion> {
readonly _V: V
readonly Uuid: unique symbol
}
5 changes: 5 additions & 0 deletions test-d/ts4.0/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,8 @@ declare const uuid6: _.Uuid<6>
const uuidToString: string = uuid
// $ExpectError
const stringToUuid: _.Uuid = 'foo'
const uuid1ToUuid: _.Uuid = uuid1
// $ExpectError
const uuidToUuid1: _.Uuid<1> = uuid
// $ExpectError
const uuid1toUuid2: _.Uuid<2> = uuid1

0 comments on commit 7f70616

Please # to comment.