Skip to content

Commit 0c5bce9

Browse files
committed
Merge pull request #4 from dphilipson/docs/remove-bad-example
Remove bad string literal example, add IDE reason
2 parents 40310db + 1635f1b commit 0c5bce9

File tree

1 file changed

+6
-17
lines changed

1 file changed

+6
-17
lines changed

README.md

+6-17
Original file line numberDiff line numberDiff line change
@@ -84,22 +84,7 @@ console.log(state);
8484

8585
### Why not string literals?
8686

87-
Using string literals throughout a program leaves it vulnerable to bugs caused by typos or
88-
incomplete refactors. For example:
89-
90-
``` javascript
91-
type Status = "RUNNING" | "STOPPED";
92-
93-
...
94-
95-
// Typo "SOTPPED" is not caught by typechecker.
96-
// Pretty bad bug- this block will never run.
97-
if (state.status === "SOTPPED") {
98-
soundTheAlarm();
99-
}
100-
```
101-
102-
Further, string literals make refactoring difficult. Suppose I have two enums:
87+
String literals make refactoring difficult. Suppose I have two enums:
10388

10489
``` javascript
10590
type Status = "RUNNING" | "STOPPED";
@@ -111,6 +96,10 @@ way to do it. I can't globally find/replace `"RUNNING"` to `"STARTED"` because i
11196
the unrelated string constants representing `TriathlonStage`. Instead, I have to examine every
11297
occurrance of the string `"RUNNING"` to see if it needs to change.
11398

99+
Another disadvantage of string literals comes when using IDE autocomplete features. It's convenient
100+
to be able to type `Status.` and have autocomplete suggest `Status.RUNNING` and `Status.STOPPED`,
101+
but with string literals no such suggestion appears with current IDEs.
102+
114103
I might try to solve both problems by introducing constants for the string literals, but this has
115104
issues as well:
116105

@@ -175,7 +164,7 @@ function Enum<V extends string>(...values: V[]): { [K in V]: K }
175164

176165
the type parameter `V` is thus inferred to be `"RUNNING" | "STOPPED"`. Then the return type
177166
`{ [K in V]: K }` is a mapped type which describes an object whose keys are the types that
178-
make up `V` and for each such key has a value equal to that key. Hence, the type of
167+
make up `V` and for each such key has a value of the same type as that key. Hence, the type of
179168
`Enum("RUNNING", "STOPPED")` is
180169

181170
``` javascript

0 commit comments

Comments
 (0)