1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-07 00:58:02 +00:00

Add Create Union Type From Constants as a TypeScript TIL

This commit is contained in:
jbranchaud
2022-09-02 16:29:03 -05:00
parent 038d2926db
commit 423b354a90
2 changed files with 39 additions and 1 deletions

View File

@@ -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)

View File

@@ -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)