diff --git a/README.md b/README.md index 8f6e11a..1663d78 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://tinyletter.com/jbranchaud). -_1110 TILs and counting..._ +_1111 TILs and counting..._ --- @@ -1013,6 +1013,7 @@ _1110 TILs and counting..._ - [Compiler Checks For Unused Params And Variables](typescript/compiler-checks-for-unused-params-and-variables.md) - [Re-Export An Imported Type](typescript/re-export-an-imported-type.md) - [Type Narrowing With Similarly Shaped Objects](typescript/type-narrowing-with-similarly-shaped-objects.md) +- [Use An Array Check For Type Narrowing](typescript/use-an-array-check-for-type-narrowing.md) - [Zero-Config Environments For Trying Out Types](typescript/zero-config-environments-for-trying-out-types.md) ### Unix diff --git a/typescript/use-an-array-check-for-type-narrowing.md b/typescript/use-an-array-check-for-type-narrowing.md new file mode 100644 index 0000000..be9ebad --- /dev/null +++ b/typescript/use-an-array-check-for-type-narrowing.md @@ -0,0 +1,33 @@ +# Use An Array Check For Type Narrowing + +If you are typing a concatenation function for melding two values together into +a single array, you may end up with a function signature like this: + +```typescript +type ConcatFunction = (value: any | any[], array: any[]) => any[]; +``` + +That first argument can be an individual value or an array of values. You'll +need to handle both scenarios in the function implementation. Using the +[`Array.isArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray) +function as a _type guard_, you can check differentiate between those two +cases. + +```typescript +const concat: ConcatFunction = (value, array) => { + if(Array.isArray(value)) { + return [...value, ...array]; + } else { + return [value, ...array]; + } +} + +concat(true, [1,2,3]); +// [true, 1, 2, 3] + +concat([1,2,3], ['a', 'b', 'c']) +// [1, 2, 3, 'a', 'b', 'c'] +``` + +This is a form of [type +narrowing](https://www.typescriptlang.org/docs/handbook/2/narrowing.html).