Skip to content

Commit bec398f

Browse files
committed
refactor: make UUID an "opaque" type
We don't have actual opaque types in TypeScript yet, but this serves as a stand-in for now. This is just one of several possible ways to do this in TypeScript; see these threads for many details: - https://codemix.com/opaque-types-in-javascript/ - microsoft/TypeScript#15807 - microsoft/TypeScript#4895 - microsoft/TypeScript#202
1 parent da12f74 commit bec398f

3 files changed

Lines changed: 8 additions & 4 deletions

File tree

‎src/jest/setup.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ global.makeNote = (template = {}) => ({
1313
body: 'note body/text',
1414
mtime: 1565214488000,
1515
path: '/fake/path.md',
16-
id: counter++,
16+
id: counter++ as UUID,
1717
tags: new Set(),
1818
text: 'note body/text',
1919
title: 'note title',

‎src/renderer/types.d.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
*/
55

66
type FrozenSet<T> = import('@wincent/frozen-set').default<T>;
7+
type UUID = import('./util/getUUID').UUID;
78

89
type Action =
910
| Readonly<{
@@ -37,7 +38,7 @@ type Note = {
3738
body: string;
3839
mtime: number;
3940
path: string;
40-
readonly id: number; // really UUID; ideally would be an opaque type
41+
readonly id: UUID;
4142
tags: Set<string>;
4243
text: string;
4344
title: string;
@@ -57,6 +58,9 @@ type Styles<T extends string = 'root'> = Readonly<
5758
}
5859
>;
5960

61+
// Via: https://codemix.com/opaque-types-in-javascript/
62+
type Opaque<K, T> = T & { __TYPE__: K };
63+
6064
// Counterpart to Readonly<T>.
6165
type Writable<T> = {
6266
-readonly [K in keyof T]: T[K];

‎src/renderer/util/getUUID.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
* @license MIT
44
*/
55

6-
export type UUID = number;
6+
export type UUID = Opaque<'UUID', number>;
77

88
/**
99
* Monotonically increasing, unique ID for each note.
@@ -14,5 +14,5 @@ let id = 0;
1414
* Returns a unique "UUID" used to identify a given note.
1515
*/
1616
export default function getUUID(): UUID {
17-
return id++;
17+
return id++ as UUID;
1818
}

0 commit comments

Comments
 (0)