-
Notifications
You must be signed in to change notification settings - Fork 0
/
enums_best_practice.ts
101 lines (92 loc) · 2.14 KB
/
enums_best_practice.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import React, { useState } from "react";
import { GenericSelect } from "./select";
import {
Book,
Laptop,
Movie,
Phone,
books,
laptops,
movies,
phones,
isBook,
isMovie,
isLaptop,
isPhone,
DataTypes
} from "./data";
enum Tabs {
"BOOKS" = "Books",
"MOVIES" = "Movies",
"LAPTOPS" = "Laptops",
"PHONES" = "Phones"
}
const valueShouldBeString = (value: string) => value;
const formatLabel = (value: DataTypes) => {
if (isBook(value)) return `${value.title}: ${value.author}`;
if (isMovie(value)) return `${value.title}: ${value.releaseDate}`;
if (isLaptop(value)) return value.model;
if (isPhone(value)) return `${value.model}: ${value.manufacture}`;
return valueShouldBeString(value);
};
const confirmImpossibleState = (tab: never) => {
throw new Error(`Reacing an impossible state because of ${tab}`);
};
const getSelect = (tab: Tabs) => {
switch (tab) {
case Tabs.BOOKS:
return (
<GenericSelect<Book>
onChange={(value) => console.info(value)}
values={books}
formatLabel={formatLabel}
/>
);
case Tabs.MOVIES:
return (
<GenericSelect<Movie>
onChange={(value) => console.info(value)}
values={movies}
formatLabel={formatLabel}
/>
);
case Tabs.LAPTOPS:
return (
<GenericSelect<Laptop>
onChange={(value) => console.info(value)}
values={laptops}
formatLabel={formatLabel}
/>
);
case Tabs.PHONES:
return (
<GenericSelect<Phone>
onChange={(value) => console.info(value)}
values={phones}
formatLabel={formatLabel}
/>
);
default:
return confirmImpossibleState(tab);
}
};
export const TabsComponent = () => {
const [tab, setTab] = useState<Tabs>(Tabs.BOOKS);
const select = getSelect(tab);
return (
<>
Select category:
<br />
<GenericSelect<Tabs>
onChange={(value) => setTab(value)}
values={Object.values(Tabs)}
formatLabel={formatLabel}
/>
<br />
<br />
List of items:
<br />
{select}
</>
);
};