1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 15:18:01 +00:00

Add Create A Union Type From An Array as a TypeScript TIL

This commit is contained in:
jbranchaud
2022-09-07 08:53:04 -07:00
parent 036a61fc40
commit 82dd650440
2 changed files with 34 additions and 1 deletions

View File

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