Skip to content

Commit 35e0567

Browse files
committed
Add Narrow The Type Of An Array To Its Values as a TypeScript TIL
1 parent 8351819 commit 35e0567

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1238 TILs and counting..._
13+
_1239 TILs and counting..._
1414

1515
---
1616

@@ -1141,6 +1141,7 @@ _1238 TILs and counting..._
11411141
- [Extract Object Type Values Into A Union Type](typescript/extract-object-type-values-into-a-union-type.md)
11421142
- [Generate Inferred Type From Zod Schema](typescript/generate-inferred-type-from-zod-schema.md)
11431143
- [Interfaces With The Same Name Are Merged](typescript/interfaces-with-the-same-name-are-merged.md)
1144+
- [Narrow The Type Of An Array To Its Values](typescript/narrow-the-type-of-an-array-to-its-values.md)
11441145
- [Re-Export An Imported Type](typescript/re-export-an-imported-type.md)
11451146
- [Type Narrowing With Const VS Let Strings](typescript/type-narrowing-with-const-vs-let-strings.md)
11461147
- [Type Narrowing With Similarly Shaped Objects](typescript/type-narrowing-with-similarly-shaped-objects.md)
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Narrow The Type Of An Array To Its Values
2+
3+
When an array of string values is defined in a TypeScript context, the inferred
4+
type will be `string[]`. That's because the values of an array can be
5+
reassigned. The most precise TypeScript can be is to say that it is an array of
6+
string.
7+
8+
```typescript
9+
const actions = ['increase', 'decrease'];
10+
// typeof actions => string[]
11+
```
12+
13+
We can freeze the array with its values using `as const`, the [const
14+
assertion](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions).
15+
This doesn't actually _freeze_ the array, but it does mark it as `readonly` for
16+
the TypeScript compiler.
17+
18+
That means we can lean on the compiler for a lot more specific feedback.
19+
Consider for instance this `reducer` function.
20+
21+
```typescript
22+
const actions = ['increase', 'decrease'] as const
23+
24+
const reducer = (action: typeof actions[number]) => {
25+
switch (action) {
26+
case 'increase':
27+
// do an increase
28+
case 'decrease':
29+
// do a decrease
30+
case 'submit': // TYPE ERROR, "submit" is not comparable to type 'increase' | 'decrease'
31+
// do a submit
32+
default:
33+
throw Error('Unrecognized action!')
34+
}
35+
}
36+
37+
// TYPE ERROR, "submit" is not comparable to type 'increase' | 'decrease'
38+
reducer('submit')
39+
```

0 commit comments

Comments
 (0)