Skip to content

Commit f050979

Browse files
authored
Merge pull request #402 from apify/lay-off-the-enums
laid off the enums
2 parents 7c91578 + 7152933 commit f050979

File tree

1 file changed

+10
-6
lines changed
  • content/academy/switching_to_typescript

1 file changed

+10
-6
lines changed

content/academy/switching_to_typescript/enums.md

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,9 @@ const fileExtensions = {
2525
};
2626
```
2727

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:
2929

3030
```TypeScript
31-
// DON'T DO THIS! Use enums instead!
32-
3331
// Since TypeScript infers these values to be just strings,
3432
// we have to create a type definition telling it that these
3533
// properties hold super specific strings.
@@ -45,6 +43,14 @@ const fileExtensions: {
4543
RUST: '.rs',
4644
PYTHON: '.py',
4745
};
46+
47+
// Or, we can just do this
48+
const fileExtensions = {
49+
JAVASCRIPT: '.js',
50+
TYPESCRIPT: '.ts',
51+
RUST: '.rs',
52+
PYTHON: '.py',
53+
} as const;
4854
```
4955

5056
> 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
5359

5460
![TypeScript autofilling the values of the fileExtensions object]({{@asset switching_to_typescript/images/constant-autofill.webp}})
5561

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.
5963

6064
## [](#creating-enums) Creating enums
6165

0 commit comments

Comments
 (0)