February 2019
Beginner
694 pages
18h 4m
English
When working with union types, the compiler will still apply its strong typing rules to ensure type safety. As an example of this, consider the following code:
function addWithUnion(
arg1 : string | number,
arg2 : string | number
) {
return arg1 + arg2;
}
Here, we are defining a function named addWithUnion, which accepts two parameters, and returns their sum. The arg1 and arg2 arguments are union types, and can therefore be either a string or a number. Compiling this code, however, will generate the following error:
error TS2365: Operator '+' cannot be applied to types 'string | number' and 'string | number'.
What the compiler is telling us here is that within the body of the function, where it attempts to add arg1 to arg2, it ...
Read now
Unlock full access