From 423b354a90c4b1197ea549dbef5030c4a7a612a2 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 2 Sep 2022 16:29:03 -0500 Subject: [PATCH] Add Create Union Type From Constants as a TypeScript TIL --- README.md | 3 +- .../create-union-type-from-constants.md | 37 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 typescript/create-union-type-from-constants.md diff --git a/README.md b/README.md index d161f6b..6c27ecc 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). -_1234 TILs and counting..._ +_1235 TILs and counting..._ --- @@ -1135,6 +1135,7 @@ _1234 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) +- [Create Union Type From Constants](typescript/create-union-type-from-constants.md) - [Extract Object Type Keys Into A Union Type](typescript/extract-object-type-keys-into-a-union-type.md) - [Extract Object Type Values Into A Union Type](typescript/extract-object-type-values-into-a-union-type.md) - [Generate Inferred Type From Zod Schema](typescript/generate-inferred-type-from-zod-schema.md) diff --git a/typescript/create-union-type-from-constants.md b/typescript/create-union-type-from-constants.md new file mode 100644 index 0000000..b66c803 --- /dev/null +++ b/typescript/create-union-type-from-constants.md @@ -0,0 +1,37 @@ +# Create Union Type From Constants + +I like to capture what I call _magic strings_ in constants (variables, really) +so that I can use them and reuse them with minimal maintenance. Minimal +maintenance because if something about the value of the string changes, I only +need to make that update in a single place. + +I want to extend this reuse to my type system as well. + +Let's say I have some constants defined like so: + +```typescript +const UPGRADE = "upgrade"; +const DOWNGRADE = "downgrade"; +``` + +I can create a union type from those values using the [`typeof` +operator](https://www.typescriptlang.org/docs/handbook/2/typeof-types.html). + +``` +type IntervalChange = typeof UPGRADE | typeof DOWNGRADE; +//=> type IntervalChange = 'upgrade' | 'downgrade' +``` + +I can then use both the constants and the type throughout my code with only one +place to update. + +```typescript +function checkForUpgrade(interval: string): IntervalChange { + // some logic + const result = ...; + + return result ? UPGRADE : DOWNGRADE; +} +``` + +[source](https://twitter.com/jbrancha/status/1565770454052249601?s=20&t=4seYY0mzoTFeDCiFwRB91g)