Skip to content

Commit b7409d9

Browse files
committed
Add Extract Object Type Keys Into A Union Type as a TypeScript TIL
1 parent 89e0c40 commit b7409d9

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-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-
_1209 TILs and counting..._
13+
_1210 TILs and counting..._
1414

1515
---
1616

@@ -1115,6 +1115,7 @@ _1209 TILs and counting..._
11151115

11161116
- [Add Types To An Object Destructuring](typescript/add-types-to-an-object-destructuring.md)
11171117
- [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)
11181119
- [Interfaces With The Same Name Are Merged](typescript/interfaces-with-the-same-name-are-merged.md)
11191120
- [Re-Export An Imported Type](typescript/re-export-an-imported-type.md)
11201121
- [Type Narrowing With Similarly Shaped Objects](typescript/type-narrowing-with-similarly-shaped-objects.md)
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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.

0 commit comments

Comments
 (0)