Okay, now it's time to move to loop. Okay, we understood how we can create if, and else. Now, it's time to understand how we can loop types to extract data. In each, you have a type, a user type that is an array that contain for each element of the array the column definition. In this case, name, first name, and value, name, last name, the value are string, and name, role can be manager or employee. We want to create a sort of get column that can be used in this way. We want to pass a user table and the name of the value, and return the definition of that column if exists. How we can do that? Using the loop. Unfortunately, in TypeScript, we cannot loop, but we can use recursion. So, how we can do that? Using list. We can check if list extend an array, and we want to pick the first element of the array, and basically spread the rest of the array inside of the rest. First, now we have to check if first extend a column with our specific name. If so, we can return first, otherwise, we want to iterate the list, the rest of the list.
How we can do that? We can call again, get column. But this time, we don't pass a list, but we pass the rest of the column that we haven't checked yet with the same name. This, as you can imagine, is a sort of recursion that, at some point, this list, if you don't have any column with that name, you will return never. Otherwise, at some point, you will return the first, and this is the result. You can basically create also other kind of loop, more simpler. For instance, in this case, we can use append. You have a tuple and the element using the spread. Basically, you can create another type with the first part of the array and the new element. In this case, we have one, two, three, and four, and the result is one, two, three, four. If you have an empty array, you can pass four. If you have a lot, you can have a lot and a lot, and blah, blah. You can also mix. You can create, find, filter, whatever you want. This is just a matter of what you need to do, and you can create your own TypeScript conditional type to create other types.
Another important part, when we work with TypeScript, we want to work with object types, and we want to manipulate them. What we want to do is to remove a field, add a field, or remove optional condition, or make everything optional, or add read-only, and blah, blah. To do that, we must know just two important things in TypeScript, the key of a keyword and the mapper type.
Comments