File tree Expand file tree Collapse file tree 2 files changed +41
-1
lines changed Expand file tree Collapse file tree 2 files changed +41
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
10
10
11
11
For a steady stream of TILs, [ sign up for my newsletter] ( https://crafty-builder-6996.ck.page/e169c61186 ) .
12
12
13
- _ 1238 TILs and counting..._
13
+ _ 1239 TILs and counting..._
14
14
15
15
---
16
16
@@ -1141,6 +1141,7 @@ _1238 TILs and counting..._
1141
1141
- [ Extract Object Type Values Into A Union Type] ( typescript/extract-object-type-values-into-a-union-type.md )
1142
1142
- [ Generate Inferred Type From Zod Schema] ( typescript/generate-inferred-type-from-zod-schema.md )
1143
1143
- [ 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 )
1144
1145
- [ Re-Export An Imported Type] ( typescript/re-export-an-imported-type.md )
1145
1146
- [ Type Narrowing With Const VS Let Strings] ( typescript/type-narrowing-with-const-vs-let-strings.md )
1146
1147
- [ Type Narrowing With Similarly Shaped Objects] ( typescript/type-narrowing-with-similarly-shaped-objects.md )
Original file line number Diff line number Diff line change
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
+ ```
You can’t perform that action at this time.
0 commit comments