Skip to content

Commit 7176281

Browse files
committed
Added solutions to 04
1 parent a83143b commit 7176281

File tree

2 files changed

+55
-3
lines changed

2 files changed

+55
-3
lines changed

exercises/04-isValidEmail.exercise.ts

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -264,8 +264,24 @@ export const onSubmit = async (values: { email: string }) => {
264264
* for plenty of type magic on their own, but when combined with opaque types
265265
* that can be extremely useful.
266266
*
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.
268285
*
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
271287
*/
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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);

0 commit comments

Comments
 (0)