From b7409d9c8fa90a3b64778c0f7aad7ac9a2e37088 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sun, 29 May 2022 18:57:47 -0500 Subject: [PATCH] Add Extract Object Type Keys Into A Union Type as a TypeScript TIL --- README.md | 3 +- ...ract-object-type-keys-into-a-union-type.md | 37 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 typescript/extract-object-type-keys-into-a-union-type.md diff --git a/README.md b/README.md index 05f9def..b8b8b22 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/typescript/extract-object-type-keys-into-a-union-type.md b/typescript/extract-object-type-keys-into-a-union-type.md new file mode 100644 index 0000000..0d036ec --- /dev/null +++ b/typescript/extract-object-type-keys-into-a-union-type.md @@ -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.