You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/academy/switching_to_typescript/enums.md
+10-6Lines changed: 10 additions & 6 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -25,11 +25,9 @@ const fileExtensions = {
25
25
};
26
26
```
27
27
28
-
No problem, this will totally work; however, the issue is that TypeScript doesn't know what these values are, but it infers them to just be strings. We can solve this by adding a type annotation with a custom type definition:
28
+
No problem, this will totally work; however, the issue is that TypeScript doesn't know what these values are - it infers them to just be strings. We can solve this by adding a type annotation with a custom type definition:
29
29
30
30
```TypeScript
31
-
// DON'T DO THIS! Use enums instead!
32
-
33
31
// Since TypeScript infers these values to be just strings,
34
32
// we have to create a type definition telling it that these
35
33
// properties hold super specific strings.
@@ -45,6 +43,14 @@ const fileExtensions: {
45
43
RUST: '.rs',
46
44
PYTHON: '.py',
47
45
};
46
+
47
+
// Or, we can just do this
48
+
const fileExtensions = {
49
+
JAVASCRIPT: '.js',
50
+
TYPESCRIPT: '.ts',
51
+
RUST: '.rs',
52
+
PYTHON: '.py',
53
+
} asconst;
48
54
```
49
55
50
56
> Using an actual concrete value such as `'.js'` or `24` or something else instead of a type name is called a [literal type](https://www.typescriptlang.org/docs/handbook/literal-types.html).
@@ -53,9 +59,7 @@ And now we'll create a variable with a hacky custom type that points to the valu
53
59
54
60

55
61
56
-
Because of the custom type definition for `fileExtensions` and the type annotation used for the `values` variable, we are getting some autofill for the variable, and the variable can only be set to values within the `fileExtensions` object. Though this implementation might be useful somewhere, it kind of sucks for a few reasons. We had to write our `fileExtensions` property twice (once for TypeScript, and another time to actually initialize the object), and had to use a weird type definition for `values`.
57
-
58
-
Don't worry, there's a better way! Enter **enums**.
62
+
Because of the custom type definition for `fileExtensions` and the type annotation used for the `values` variable, we are getting some autofill for the variable, and the variable can only be set to values within the `fileExtensions` object. Though this implementation works, TypeScript offers a unique new feature called **enums** that was designed just for these use cases.
0 commit comments