File tree Expand file tree Collapse file tree 2 files changed +39
-1
lines changed Expand file tree Collapse file tree 2 files changed +39
-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
- _ 1209 TILs and counting..._
13
+ _ 1210 TILs and counting..._
14
14
15
15
---
16
16
@@ -1115,6 +1115,7 @@ _1209 TILs and counting..._
1115
1115
1116
1116
- [ Add Types To An Object Destructuring] ( typescript/add-types-to-an-object-destructuring.md )
1117
1117
- [ Compiler Checks For Unused Params And Variables] ( typescript/compiler-checks-for-unused-params-and-variables.md )
1118
+ - [ Extract Object Type Keys Into A Union Type] ( typescript/extract-object-type-keys-into-a-union-type.md )
1118
1119
- [ Interfaces With The Same Name Are Merged] ( typescript/interfaces-with-the-same-name-are-merged.md )
1119
1120
- [ Re-Export An Imported Type] ( typescript/re-export-an-imported-type.md )
1120
1121
- [ 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
+ # Extract Object Type Keys Into A Union Type
2
+
3
+ The [ object type] ( https://www.typescriptlang.org/docs/handbook/2/objects.html )
4
+ is a way of grouping types together to represent something more complex. For
5
+ instance, it may be used to represent the types of events that a reducer can
6
+ process.
7
+
8
+ ``` typescript
9
+ interface GlobalReducerEvent {
10
+ ADD_TODO: {
11
+ text: string
12
+ }
13
+ LOG_IN: {
14
+ email: string
15
+ }
16
+ DELETE_TODO: {
17
+ todo_id: number
18
+ }
19
+ }
20
+ ```
21
+
22
+ From this object type, I can extract a [ union
23
+ type] ( https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types )
24
+ of the keys, perhaps as part of building [ a more useful type
25
+ mapping] ( https://dev.to/jbranchaud/breaking-down-a-complex-mapped-type-in5 ) .
26
+
27
+ This can be done with
28
+ [ ` keyof ` ] ( https://www.typescriptlang.org/docs/handbook/2/keyof-types.html ) .
29
+
30
+ ``` typescript
31
+ type EventTypes = keyof GlobalReducerEvent ;
32
+ // => 'ADD_TODO' | 'LOG_IN' | 'DELETE_TODO'
33
+ ```
34
+
35
+ The ` keyof ` type operator extracts each key of the ` GlobalReducerEvent ` into a
36
+ union type. This can be mixed into other types in all sorts of interesting
37
+ ways.
You can’t perform that action at this time.
0 commit comments