mirror of
https://github.com/jbranchaud/til
synced 2026-01-09 18:18:02 +00:00
Add Add Generic Typing To An Anonymous Function 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).
|
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
|
### 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)
|
- [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)
|
- [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)
|
- [Create A Non-Empty Array Type](typescript/create-a-non-empty-array-type.md)
|
||||||
|
|||||||
29
typescript/add-generic-typing-to-an-anonymous-function.md
Normal file
29
typescript/add-generic-typing-to-an-anonymous-function.md
Normal file
@@ -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
|
||||||
|
<T>() => {}
|
||||||
|
```
|
||||||
|
|
||||||
|
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 = <T>(arr: Array<T>, n: number): Array<T> => {
|
||||||
|
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.
|
||||||
Reference in New Issue
Block a user