If you already have a subscription, you can sign in.
Enjoy free content straight from your inbox 💌
00:00
Here we have a variable representing the value of a dice of type number. Then we have a utility function roll dice, which updates the value of the Tice with a new random value. To ensure that dice is always a valid number, we do an initial roll of the dice. Now at this point, if you try to read the value of the dice, we get a compiler error from TypeScript. The error message indicates that variable dice is being used before it has been assigned. The source of this error is the fact that we are not doing a direct assignment of the variable at the point of declaration and only doing one later on through a function call.
00:34
Since TypeScript doesn't track the mutating side effects of a function, it thinks that dice might still be undefined. We can overcome this error with a non null assertion as we have seen in a previous lesson. It does get rid of the error. However, if you try to roll the dice again and then read its value, TypeScript still thinks that dice might be undefined as it has still never been initialized directly. So let's get rid of our normal assertion and look at an alternative fix. We can use an exclamation mark after the variable name at the point of declaration
01:06
to tell TypeScript that this variable is definitely assigned. This exclamation mark at the point of declaration is known as a definite assignment assertion, and now TypeScript no longer complains that the variable is used before assignment. Just like other assertions, the definite assignment assertion is compiled time only, and it is up to you to ensure correctness. Now, definite assignment can also be used with members of a class. So let's look at another example. Hey, we have a class representing a point in two dimensional space with members X
01:39
and Y that we initialize to random values in the constructor. This class also provides the utility method to REIT initialize the X and Y members to new random values. At this point, you can see the code duplication between the constructor and the move random method. We can get rid of this duplication by simply invoking the move random method from the constructor. However, this raises a compiler error for the members X and Y. And if you look at the error message, you can see that it is complaining that the members X and Y do not have an initializer and are not assigned to a value in the constructor.
02:14
This is similar to the error message we saw in our previous example and the cause once more is the redirection introduced by the function call. The fix is once more the same. That is we do a definite assignment assertion by adding an exclamation mark after the member declarations.