diff --git a/README.md b/README.md index 06267c5..c84c4e3 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). -_1241 TILs and counting..._ +_1242 TILs and counting..._ --- @@ -1138,6 +1138,7 @@ _1241 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 A Union Type From An Array](typescript/create-a-union-type-from-an-array.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) diff --git a/typescript/create-a-union-type-from-an-array.md b/typescript/create-a-union-type-from-an-array.md new file mode 100644 index 0000000..d8a8b1e --- /dev/null +++ b/typescript/create-a-union-type-from-an-array.md @@ -0,0 +1,32 @@ +# Create A Union Type From An Array + +Let's say we have an array of _actions_ that our program knows how to handle. + +```typescript +// inferred type: string[] +const actions = ['increase', 'decrease', 'reset']; +``` + +The inferred type of that array is `string[]` which is a pretty wide type. We +can't do much with it. We can prevent the widening of this array's inferred +type using `as const`. + +```typescript +// inferred type: readonly ['increase', 'decrease', 'reset'] +const actions = ['increase', 'decrease', 'reset'] as const; +``` + +That inferred type is specific enough that we can do something with it, like +create a union type. + +```typescript +const actions = ['increase', 'decrease', 'reset'] as const; + +type Actions = typeof actions[number]; +//=> type Actions = 'increase' | 'decrease' | 'reset' +``` + +We could use the `Actions` type to specify that a function only takes values +that correspond to known actions, for instance. + +[source](https://bobbyhadz.com/blog/typescript-create-union-type-from-array)