mirror of
https://github.com/jbranchaud/til
synced 2026-01-02 22:58:01 +00:00
Add Narrow The Type Of An Array To Its Values as a TypeScript TIL
This commit is contained in:
@@ -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).
|
||||
|
||||
_1238 TILs and counting..._
|
||||
_1239 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -1141,6 +1141,7 @@ _1238 TILs and counting..._
|
||||
- [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)
|
||||
- [Interfaces With The Same Name Are Merged](typescript/interfaces-with-the-same-name-are-merged.md)
|
||||
- [Narrow The Type Of An Array To Its Values](typescript/narrow-the-type-of-an-array-to-its-values.md)
|
||||
- [Re-Export An Imported Type](typescript/re-export-an-imported-type.md)
|
||||
- [Type Narrowing With Const VS Let Strings](typescript/type-narrowing-with-const-vs-let-strings.md)
|
||||
- [Type Narrowing With Similarly Shaped Objects](typescript/type-narrowing-with-similarly-shaped-objects.md)
|
||||
|
||||
39
typescript/narrow-the-type-of-an-array-to-its-values.md
Normal file
39
typescript/narrow-the-type-of-an-array-to-its-values.md
Normal file
@@ -0,0 +1,39 @@
|
||||
# Narrow The Type Of An Array To Its Values
|
||||
|
||||
When an array of string values is defined in a TypeScript context, the inferred
|
||||
type will be `string[]`. That's because the values of an array can be
|
||||
reassigned. The most precise TypeScript can be is to say that it is an array of
|
||||
string.
|
||||
|
||||
```typescript
|
||||
const actions = ['increase', 'decrease'];
|
||||
// typeof actions => string[]
|
||||
```
|
||||
|
||||
We can freeze the array with its values using `as const`, the [const
|
||||
assertion](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions).
|
||||
This doesn't actually _freeze_ the array, but it does mark it as `readonly` for
|
||||
the TypeScript compiler.
|
||||
|
||||
That means we can lean on the compiler for a lot more specific feedback.
|
||||
Consider for instance this `reducer` function.
|
||||
|
||||
```typescript
|
||||
const actions = ['increase', 'decrease'] as const
|
||||
|
||||
const reducer = (action: typeof actions[number]) => {
|
||||
switch (action) {
|
||||
case 'increase':
|
||||
// do an increase
|
||||
case 'decrease':
|
||||
// do a decrease
|
||||
case 'submit': // TYPE ERROR, "submit" is not comparable to type 'increase' | 'decrease'
|
||||
// do a submit
|
||||
default:
|
||||
throw Error('Unrecognized action!')
|
||||
}
|
||||
}
|
||||
|
||||
// TYPE ERROR, "submit" is not comparable to type 'increase' | 'decrease'
|
||||
reducer('submit')
|
||||
```
|
||||
Reference in New Issue
Block a user