Clean up your TypeScript code with type guards

Tim Mouskhelichvili
Tim Mouskhelichvili
1 minute to read

I hope you are doing well.

When I review TypeScript code, I often see code with multiple unnecessary type castings.

Let's have an example.

typescript type guard

As you can see, this is a pretty standard function that calls an animal's special action based on its type.

Notice the MULTIPLE type castings? Wouldn't it be better if the animal's type was inferred by the compiler instead of doing type casting? Of course, it would.

That's why we need to define a type guard.

A type guard narrows the type of a variable within a conditional block.

Let's replace type castings with type guards.

typescript type guard

As you can see, the code is now much cleaner and readable!

Articles

Here is the latest article on the blog:

Thank you for reading.

See you next week!

Tim M.

Comments (0)
Reply to:
Page content
  1. Articles