diff --git a/README.md b/README.md index 3d842d3..6ae5750 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). -_1291 TILs and counting..._ +_1292 TILs and counting..._ --- @@ -1191,6 +1191,7 @@ _1291 TILs and counting..._ ### TypeScript +- [Add Generic Typing To An Anonymous Function](typescript/add-generic-typing-to-an-anonymous-function.md) - [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 Non-Empty Array Type](typescript/create-a-non-empty-array-type.md) diff --git a/typescript/add-generic-typing-to-an-anonymous-function.md b/typescript/add-generic-typing-to-an-anonymous-function.md new file mode 100644 index 0000000..e9ec62b --- /dev/null +++ b/typescript/add-generic-typing-to-an-anonymous-function.md @@ -0,0 +1,29 @@ +# Add Generic Typing To An Anonymous Function + +A common pattern, especially when dealing with collections of data (read: +arrays), is to have a function that can transform an array of any type of data. +In order to keep this kind of function general-purpose and have it preserve +types, we'll need to use generics. + +For an anonymous function to work with a generic type, it needs to open with a +signature for the generic type: + +```typescript +() => {} +``` + +With that in mind, we can write a function that accepts an array of type `T`, +does something to that collection, and then returns an array of type `T`. + +For instance, here is a function that takes the first `n` elements from the +array and returns them. + +```typescript +const take = (arr: Array, n: number): Array => { + return arr.slice(0, n) +} +``` + +This both enforces and preserves the type of the array. It works well for +situations where the array is a bunch of complex objects with specific types +like we'd get from a Prisma query.