Types and Functional Programming are a great combination to get feedback quickly about types that don't make sense and compose functionality to get a desired result. fp-ts is a very powerful library that provides the tools to work with types and functional programming in an outstanding way. Let’s see it in action in a React Application to make it more type safe and composable by defining impossible states that will reduce the possibility of edge cases in our application.
Making Impossible States with fp-ts and TypeScript in a React Application
AI Generated Video Summary
1. Introduction to TypeScript and FPTS
My name is Cristian Motochi and I am a software developer at Stackbuilders. And here I've been learning about Haskell and PureScript.
And there are two things that I like about these languages that I always try to make good languages or frameworks. First is static typing because that helps me to get errors as I am developing code and if something doesn't type check, OK, I won't be able to execute the code. I would have to fix that first. And functional programming because by composing functions I can define my program. I think the best way to get static typing in a realtification is with TypeScript. The type system is very rich. We have TypeAlysis, TypeUnions, interfaces, TypeVariables, and many more things. And combining TypeScript with Rambda or Rampdas code, we will get functional programming.
2. Types and State Selection
We can have states that we may not want in our application. For example, we don't want the users to have the list of extras if they haven't selected the main ingredient. Let's think about one thing we can do to get a type error if we define this type of state. We have another scenario where the user hasn't selected the main ingredient but they do have selected their second ingredient. So let's come up with a better type that would complain in these cases. Now we can define smart constructors and other functions around this type, and even define type instances for this data type.
And the list of extras. And this type could work, nevertheless. We can have states that we may not want in our application. For example, we don't want the users to have the list of extras if they haven't selected the main ingredient. OK, so we don't want this state to happen. That's because one complaint we'll get at some point with this case.
If we define the type... If we define this type of a slash. So, let's think about one thing we do to get a type error if we define this type of state. OK, we could think about this one. The main ingredient is not going to be only the ingredient, it's going to be the ingredient and the list of extra options. Yeah so if we try to define something like this, with this direct type, this time we will get a type error. And that could be the problem.