The reason is when logging direction
, it is randomly either a string, or left unassigned (with the default undefined
value). In this case you'll still get an error that direction
is used before being assigned, because it's not always assigned. In other words, TypeScript knows that not every possible route through the program assigns to the variable before it is used.
It's worth noting that later on we'll come across cases where it's useful to leave a typed variable unassigned. In Construct it is particularly useful to declare a variable that will store an object instance, but not assign it until the layout starts and the object is created. TypeScript allows such cases, even though there is a period of time the variable is left as undefined
. This is because the benefits outweigh the costs - it's very convenient and generally isn't a problem.
Conclusion
In this part we've covered:
- Union types
- Type narrowing
- Literal types
- Type aliases
- The special
any
and unknown
types
- The special
undefined
and null
values
- Some more details about initializing variables
This section was quite theoretical. You may be keen to write some more useful code samples! However what we covered here is fundamental to the workings of TypeScript, so it was important to take a bit of a detour to cover it. Now you know these essential details about TypeScript, we're ready to move on to our next important programming concept: functions!
Learn more
If you want to dig deeper, you can learn more about the features mentioned in this guide at the following links: