When working with union types in TypeScript, we will often come into a situation where we need to use type guard to please the TypeScript compiler. The compiler always apply its strong typing rules to ensure type safety.
Take a look at this code:
This is a function that accepts two parameters and returns their sum. The
arg2 parameters are union types. They can hold either a string or a number. Unfortunately, when we try to compile this code, we’ll get the following error:
The compiler is telling us that it cannot tell what type it should use when it attempts to add
arg2. Is it supposed to add number to a string, a string to a number, a string to a string, or a number to a number?
This is where type guards come in. Type guard performs a check on our type, and then guarantees that type within its scope.
Implementing Type Guard
Let’s rewrite our
add function to use type guard.
typeof keyword to test
arg1’s type. If the type is a string, then the compiler knows that within the code block following it,
arg1 is definitely a string, and will therefore treat
arg1 as a string.
The second if statement is similar. We have two
typeof checks to check whether both
arg2 are of type number. If they are both numbers, then the compiler knows that
arg2 are definitely of type number within the following code block.
Now, let’s test the function!
We can see that the first call to
add is using two arguments that are strings. The code identifies the first argument as being of type string and therefore enters the first if statement block. The concatenation of the string “1” with “2” results in the string “12”.
add uses two numbers as arguments, and our code identifies both arguments as numbers, and as such adds the value 1 and the value 2, resulting in 3.
add uses a number as the first argument and a string as the second. The code therefore falls through to the default code, treating both arguments as strings.