13 likes
·
351 reads
5 comments
🔥🔥🔥
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
This is interesting. Thanks for sharing it! What would be the advantage of using this over includes and returning a boolean?
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 explanation Furkan Emin Can.
I looked at your example once more, and I think it does more (which completely justifies the different typing) compared to my simple example. Yours returns the actual collaborator type if the supplied data.collaborator.type
matches a collaborator type.
In my example, I simply want to know if the value of data.collaborator.type
is an external collaborator. Since it's either yes or no, boolean
gives sufficient type narrowing (true/false).