File tree Expand file tree Collapse file tree 2 files changed +55
-3
lines changed Expand file tree Collapse file tree 2 files changed +55
-3
lines changed Original file line number Diff line number Diff line change @@ -264,8 +264,24 @@ export const onSubmit = async (values: { email: string }) => {
264
264
* for plenty of type magic on their own, but when combined with opaque types
265
265
* that can be extremely useful.
266
266
*
267
- * 🕵️♂️ Discuss what you might use opaque types for. Some ideas:
267
+ */
268
+
269
+ /**
270
+ * 🕵️♂️ Stretch goal 1:
271
+ *
272
+ * Create two Opaque types - one called PostId, another called UserId.
273
+ * Create two functions - getPostById and getUserById. Make each only
274
+ * take their specific types of id as a parameter.
275
+ *
276
+ * Try calling getUserById("123"); You'll notice that you get an error:
277
+ *
278
+ * Argument of type 'string' is not assignable to parameter of type 'UserId'.
279
+ *
280
+ * Discuss the best way to solve this. You could consider:
281
+ *
282
+ * A type predicate.
283
+ * Casting using as.
284
+ * An assertion function.
268
285
*
269
- * - Ensuring a user exists in the database before acting on it
270
- * - Separating out different types of entity ids (PostId, UserId)
286
+ * Solution #1
271
287
*/
Original file line number Diff line number Diff line change
1
+ /**
2
+ * #1 below:
3
+ */
4
+
5
+ export type Opaque < TValue , TOpaque > = TValue & {
6
+ __ : TOpaque ;
7
+ } ;
8
+
9
+ type PostId = Opaque < string , "PostId" > ;
10
+ type UserId = Opaque < string , "UserId" > ;
11
+
12
+ const getUserById = ( id : UserId ) => { } ;
13
+ const getPostById = ( id : PostId ) => { } ;
14
+
15
+ // Method 1 - assertion function
16
+
17
+ function assertIsUserId ( id : any ) : asserts id is UserId { }
18
+
19
+ const id = "123" ;
20
+ assertIsUserId ( id ) ;
21
+ getUserById ( id ) ;
22
+
23
+ // Method 2 - type predicate
24
+
25
+ function isUserId ( id : any ) : id is UserId {
26
+ return true ;
27
+ }
28
+
29
+ const id2 = "123" ;
30
+ if ( isUserId ( id2 ) ) {
31
+ getUserById ( id2 ) ;
32
+ }
33
+
34
+ // Method 3 - casting
35
+
36
+ getUserById ( "123" as UserId ) ;
You can’t perform that action at this time.
0 commit comments