Skip to content

Commit 22e4a1e

Browse files
committed
Add Use An Array Check For Type Narrowing as a typescript til
1 parent ff10e35 commit 22e4a1e

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1212

13-
_1110 TILs and counting..._
13+
_1111 TILs and counting..._
1414

1515
---
1616

@@ -1013,6 +1013,7 @@ _1110 TILs and counting..._
10131013
- [Compiler Checks For Unused Params And Variables](typescript/compiler-checks-for-unused-params-and-variables.md)
10141014
- [Re-Export An Imported Type](typescript/re-export-an-imported-type.md)
10151015
- [Type Narrowing With Similarly Shaped Objects](typescript/type-narrowing-with-similarly-shaped-objects.md)
1016+
- [Use An Array Check For Type Narrowing](typescript/use-an-array-check-for-type-narrowing.md)
10161017
- [Zero-Config Environments For Trying Out Types](typescript/zero-config-environments-for-trying-out-types.md)
10171018

10181019
### Unix
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Use An Array Check For Type Narrowing
2+
3+
If you are typing a concatenation function for melding two values together into
4+
a single array, you may end up with a function signature like this:
5+
6+
```typescript
7+
type ConcatFunction = (value: any | any[], array: any[]) => any[];
8+
```
9+
10+
That first argument can be an individual value or an array of values. You'll
11+
need to handle both scenarios in the function implementation. Using the
12+
[`Array.isArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)
13+
function as a _type guard_, you can check differentiate between those two
14+
cases.
15+
16+
```typescript
17+
const concat: ConcatFunction = (value, array) => {
18+
if(Array.isArray(value)) {
19+
return [...value, ...array];
20+
} else {
21+
return [value, ...array];
22+
}
23+
}
24+
25+
concat(true, [1,2,3]);
26+
// [true, 1, 2, 3]
27+
28+
concat([1,2,3], ['a', 'b', 'c'])
29+
// [1, 2, 3, 'a', 'b', 'c']
30+
```
31+
32+
This is a form of [type
33+
narrowing](https://www.typescriptlang.org/docs/handbook/2/narrowing.html).

0 commit comments

Comments
 (0)