@femincan
A front-end developer who loves reading, writing, and calisthenics.
Hello, I'm Furkan Emin Can.
I'm a self-taught, passionate front-end developer who enjoys writing TypeScript and strives to become a better developer.
In my free time, I love practicing calisthenics and enjoy reading programming blogs that help me improve my skills.
Nothing here yet.
For the first part of your question, the reason why I didn't use Array.includes is because of a problem with TypeScript. As far as I understand, TypeScript doesn't allow us to use a more generic typed search parameter for a more explicitly typed array in the Array.includes . So we can't use the type string with an array typed ("External Editor" | "External Administrator")[] . As a workaround we can set the parameter type as any , but I thought Array.some is more straightforward to work with (we don't need to disable type checking), and also I couldn't find any performance difference between the two. For the second part of the question, returning a boolean doesn't give us any type narrowing. If you use the function with an if statement, inside the statement, the type of data.collaborator.type is still string . On the contrary, returning type predicate gives us type narrowing. If we call this function with an if statement, inside the statement, the type of data.collaborator.type is narrowed to "External Editor" | "External Administrator" . There is a visualization in the TS Playground that shows the result of narrowing the type. As I said, I think this approach is more suitable for the TypeScript side, for the JavaScript side there is nearly no difference.
Thanks for the great article Ákos Kőműves . I've played with your example and converted it to a type predicate function. The isCollaboratorExternal function accepts a collaborator parameter with type string and uses the Array.some function (because of this issue ) to check if externalCollaboratorTypes has the collaboratorType and returns the type predicate. Thus, after the check operation the type of data.collaborator.type will be "External Editor" | "External Administrator" . I think types are more aligned with the logic in this solution. Here is the link for TypeScript Playground: TS Playground
Thanks for the comment Ender. As I have mentioned in the article, If I didn't use the "Cancelling the button during the ongoing request" approach, I would use AbortController with Axios. But I didn't choose this approach for simplicity.