Tutorials on Generics

Learn about Generics from fellow newline community members!

  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL
  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL

How to Use fetch with TypeScript

The main problem with fetch function is that it isn't a generic function . This makes it harder to type response data without writing additional wrappers. We can create a wrapper-module to avoid this problem. Let's create a function request that will handle network requests: Now we can call this function as we would call fetch : Or, since it is an async function we can use await : Right now the request function doesn't handle errors. To solve that we have 2 options: There are no obligatory rules for this but Single Responsibility Principle tells us not to mix those concerns in a single function. However, we will take a look at both ways. The first one is to handle errors inside of the request function: We can use catch to handle unresolved promises. There is a catch though (no pun intended). The first issue we can solve making the function async and using try-catch : However, this doesn't solve the second issue with not knowing how to handle the error. We can handle some basic network errors (Page Not Found, Bad Request) but we cannot handle any business-logic errors. With async/await approach, we can handle errors outside of the request function: We can also pre-define some basic request-methods, like get and post : We will use them like this:

How to Use Generics in TypeScript

Generics in TypeScript is a way to make your code more abstract and reusable. Let's say you want to create a function that returns a first element from a given list: How to type it? We cannot know beforehand list of what type will be given. We could use overloads to enumerate every possible type we accept: ...Or we could use a union type: ...But all of those ways have a common issue. If we want to pass, for example, an object, we have to define it in the type manually. This isn't convenient, and TypeScript has a better way to do it. Generic type is a type that accepts arguments and uses them in some way. In the case of our head function, we can declare: The angle brackets define a type-parameter . This parameter is used by TypeScript compiler to define the TEntity type later. So, when we use this function like this: ...the TEntity becomes a number . When we use the function like this: ...the TEntity becomes a string . We don't have to manually define a type now, since TypeScript will automatically defer it from the argument. It will even defer a union type for you if pass an array of elements with different types. With generics, you can describe custom types and interfaces in more abstract way. Let's say you want to create a type-alias for array and call it List . You would use this type somehow like this: With TypeScript, you can define a generic type for this: You can read it as a ”type-function“. It takes an argument TEntity and returns an array of TEntity . Same with interfaces. You can define an interface with type-parameters to set a type which this interface can work with: Most of the time generic types and interfaces are used to define type-constraints. You can also set constraints for your generic types to make sure it is used properly. Let's say you want your EventHandler to be used only with MouseEvent or KeyboardEvent . Then, you can specify those types as a constraint : You can even define a constraint based on a type-parameter! Let's say you want to create a select function, that returns the value of a property in an object: You don't know beforehand what type of object will be passed to this function. However, you can set a constraint on key argument to ensure selecting only from existing properties on the object : When you use this function with an object: This is also useful when coding in IDE with auto-completion because it will allow you to select a seconds argument: Imagine you need to convert some type in a way to make every field optional. TypeScript already has a Partial utility type . Utility types are generic types that perform some transformation on a given type-parameters. In our case, Partial makes every key in a given object optional. There are many other useful utility types described in the TypeScript documentation .

Thumbnail Image of Tutorial How to Use Generics in TypeScript

I got a job offer, thanks in a big part to your teaching. They sent a test as part of the interview process, and this was a huge help to implement my own Node server.

This has been a really good investment!

Advance your career with newline Pro.

Only $30 per month for unlimited access to over 60+ books, guides and courses!

Learn More