mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 07:08:01 +00:00
Add Extract Object Type Keys Into A Union Type as a TypeScript TIL
This commit is contained in:
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
|
||||
|
||||
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
|
||||
|
||||
_1209 TILs and counting..._
|
||||
_1210 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -1115,6 +1115,7 @@ _1209 TILs and counting..._
|
||||
|
||||
- [Add Types To An Object Destructuring](typescript/add-types-to-an-object-destructuring.md)
|
||||
- [Compiler Checks For Unused Params And Variables](typescript/compiler-checks-for-unused-params-and-variables.md)
|
||||
- [Extract Object Type Keys Into A Union Type](typescript/extract-object-type-keys-into-a-union-type.md)
|
||||
- [Interfaces With The Same Name Are Merged](typescript/interfaces-with-the-same-name-are-merged.md)
|
||||
- [Re-Export An Imported Type](typescript/re-export-an-imported-type.md)
|
||||
- [Type Narrowing With Similarly Shaped Objects](typescript/type-narrowing-with-similarly-shaped-objects.md)
|
||||
|
||||
37
typescript/extract-object-type-keys-into-a-union-type.md
Normal file
37
typescript/extract-object-type-keys-into-a-union-type.md
Normal file
@@ -0,0 +1,37 @@
|
||||
# Extract Object Type Keys Into A Union Type
|
||||
|
||||
The [object type](https://www.typescriptlang.org/docs/handbook/2/objects.html)
|
||||
is a way of grouping types together to represent something more complex. For
|
||||
instance, it may be used to represent the types of events that a reducer can
|
||||
process.
|
||||
|
||||
```typescript
|
||||
interface GlobalReducerEvent {
|
||||
ADD_TODO: {
|
||||
text: string
|
||||
}
|
||||
LOG_IN: {
|
||||
email: string
|
||||
}
|
||||
DELETE_TODO: {
|
||||
todo_id: number
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
From this object type, I can extract a [union
|
||||
type](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types)
|
||||
of the keys, perhaps as part of building [a more useful type
|
||||
mapping](https://dev.to/jbranchaud/breaking-down-a-complex-mapped-type-in5).
|
||||
|
||||
This can be done with
|
||||
[`keyof`](https://www.typescriptlang.org/docs/handbook/2/keyof-types.html).
|
||||
|
||||
```typescript
|
||||
type EventTypes = keyof GlobalReducerEvent;
|
||||
//=> 'ADD_TODO' | 'LOG_IN' | 'DELETE_TODO'
|
||||
```
|
||||
|
||||
The `keyof` type operator extracts each key of the `GlobalReducerEvent` into a
|
||||
union type. This can be mixed into other types in all sorts of interesting
|
||||
ways.
|
||||
Reference in New Issue
Block a user