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: book-content/chapters/09-typescript-only-features.md
+30-6Lines changed: 30 additions & 6 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -230,13 +230,26 @@ logStatus(0);
230
230
231
231
If we call it with a number that isn't a member of the enum, TypeScript will report an error:
232
232
233
-
```typescript
234
-
logStatus(3); // Argument of type '3' is not assignable to parameter of type 'AlbumStatus'.
233
+
```ts twoslash
234
+
// @errors: 2345
235
+
enumAlbumStatus {
236
+
NewRelease=0,
237
+
OnSale=1,
238
+
StaffPick=2,
239
+
}
240
+
241
+
function logStatus(genre:AlbumStatus) {
242
+
console.log(genre);
243
+
}
244
+
245
+
// ---cut---
246
+
logStatus(3);
235
247
```
236
248
237
249
This is different from string enums, which only allow the enum members to be used as types:
238
250
239
-
```typescript
251
+
```ts twoslash
252
+
// @errors: 2345
240
253
enumAlbumStatus {
241
254
NewRelease="NEW_RELEASE",
242
255
OnSale="ON_SALE",
@@ -248,7 +261,7 @@ function logStatus(genre: AlbumStatus) {
248
261
}
249
262
250
263
logStatus(AlbumStatus.NewRelease);
251
-
logStatus("NEW_RELEASE");// Argument of type '"NEW_RELEASE"' is not assignable to parameter of type 'AlbumStatus'.
264
+
logStatus("NEW_RELEASE");
252
265
```
253
266
254
267
The way string enums behave feels more natural - it matches how enums work in other languages like C# and Java.
@@ -259,14 +272,25 @@ In fact, string enums are unique in TypeScript because they're compared _nominal
259
272
260
273
This means that two string enums with the same members are considered different types if they have different names:
261
274
262
-
```typescript
275
+
```ts twoslash
276
+
// @errors: 2345
277
+
enumAlbumStatus {
278
+
NewRelease="NEW_RELEASE",
279
+
OnSale="ON_SALE",
280
+
StaffPick="STAFF_PICK",
281
+
}
282
+
function logStatus(genre:AlbumStatus) {
283
+
console.log(genre);
284
+
}
285
+
286
+
// ---cut---
263
287
enumAlbumStatus2 {
264
288
NewRelease="NEW_RELEASE",
265
289
OnSale="ON_SALE",
266
290
StaffPick="STAFF_PICK",
267
291
}
268
292
269
-
logStatus(AlbumStatus2.NewRelease);// Argument of type 'AlbumStatus2' is not assignable to parameter of type 'AlbumStatus'.
293
+
logStatus(AlbumStatus2.NewRelease);
270
294
```
271
295
272
296
For those of us used to structural typing, this can be a bit of a surprise. But to developers used to enums in other languages, string enums will feel the most natural.
0 commit comments