質問するログイン新規登録

回答編集履歴

1

テキスト修正

2019/10/20 13:38

投稿

jun68ykt
jun68ykt

スコア9058

answer CHANGED
@@ -5,6 +5,39 @@
5
5
 
6
6
  - **TypeScript Deep Dive 日本語版:** [文字列ベースの列挙型](https://typescript-jp.gitbook.io/deep-dive/type-system/literal-types#bsuno)
7
7
 
8
- に記載されている `strEnum` ユーティリティを使ったサンプルと同じような方法で、`type Color` を作成するのはいかがでしょうか?
8
+ に記載されている下記のサンプルと同じような方法で、ご質問に挙げられている `type Color` を作成するのはいかがでしょうか?
9
9
 
10
+ ```typescript
11
+ /** Utility function to create a K:V from a list of strings */
12
+ function strEnum<T extends string>(o: Array<T>): {[K in T]: K} {
13
+ return o.reduce((res, key) => {
14
+ res[key] = key;
15
+ return res;
16
+ }, Object.create(null));
17
+ }
18
+
19
+ /**
20
+ * Sample create a string enum
21
+ */
22
+
23
+ /** Create a K:V */
24
+ const Direction = strEnum([
25
+ 'North',
26
+ 'South',
27
+ 'East',
28
+ 'West'
29
+ ])
30
+ /** Create a Type */
31
+ type Direction = keyof typeof Direction;
32
+
33
+ /**
34
+ * Sample using a string enum
35
+ */
36
+ let sample: Direction;
37
+
38
+ sample = Direction.North; // Okay
39
+ sample = 'North'; // Okay
40
+ sample = 'AnythingElse'; // ERROR!
41
+ ```
42
+
10
43
  参考になれば幸いです。