panastock.blogg.se

Express typescript
Express typescript













express typescript

I hope you found this useful! Personally, it's my favourite way to add input validation if you're using typescript. This whole example is available as a repo if you're having issues setting things up. The easiest way to show this is with an example: type RequestBody = Request interface UserBody ) Most issues with Express crop up with badly (not) checked inputs to endpoints.

express typescript

If we apply all these new types in our code, our code should look like this.Since this is a bit of a long post with multiple files I've provided a sample repo so you can see the final code in action, in case the post gets a bit too hard to follow. And, lastly, the Dog type alias is the combination of two interfaces BaseParams and DogDetails we achieved this by using the & intersection type. The DogBreed type alias is also a helper type that referenced in the Pagination interface and also the DogDetails interface. The interface Empty is a helper interface type that we will use for empty objects. The interface Pagination is the type we will use for the position ReqQuery, this type has a property breed the references another custom type that we will be talking about soon. The interface APIResponse is the type that we will use for the ResBody position, this type also has a generic just like the type BaseParams, the generic ResultType type will be the type of the data property. The interface DogDetails is the type we will use for the ReqBody position. First, the interface BaseParams is the type we will provide to the Params position, the BaseParams has Generic type IDType which has a default value of type number you can also provide a different type for the id by passing another type here BaseParams. Ok, I will explain all these new types that you see. Enter fullscreen mode Exit fullscreen mode















Express typescript