-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02.2.discriminated-unions-normalization.ts
77 lines (68 loc) · 1.96 KB
/
02.2.discriminated-unions-normalization.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import {
ICreativeData,
IFacebookCreativeData,
IInstagramCreativeData,
IYoutubeCreativeData
} from "./interfaces";
// http://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unions
// TypeScript control flow analysis can "narrow down" not only with typeguards,
// But also with discrimination
export function getIdForCreative(creative: ICreativeData): string {
// using the creative_network literal string as discriminator
switch (creative.creative_network) {
case "facebook":
return creative.fb_post_entity_id;
case "instagram":
return creative.ig_media_id;
// commnet this out!
// typescript helps me to make sure i've coverd all of the possible cases
case "youtube":
return creative.yt_video_id;
}
}
export function getIdForCreativeUsingInOperator(
creative: ICreativeData
): string {
// using in operator as descriminator
if ("fb_post_entity_id" in creative) {
return creative.fb_post_entity_id;
} else if ("ig_media_id" in creative) {
return creative.ig_media_id;
} else {
return creative.yt_video_id;
}
}
interface INormelizedCreative {
network: string;
id: string;
image: string;
caption: string;
}
export function normelizeCreative(
creative: ICreativeData
): INormelizedCreative {
switch (creative.creative_network) {
// commnet this out!
case "youtube":
return {
network: creative.creative_network,
id: creative.yt_video_id,
image: creative.yt_video_thumbnail_img_url,
caption: creative.yt_video_title
};
case "facebook":
return {
network: creative.creative_network,
id: creative.fb_post_entity_id,
image: creative.fb_post_img_url,
caption: creative.fb_post_caption
};
case "instagram":
return {
network: creative.creative_network,
id: creative.ig_media_id,
image: creative.ig_media_image_url,
caption: creative.ig_media_text
};
}
}