If you already have a subscription, you can sign in.
Enjoy free content straight from your inbox 💌
00:00
Here we have a type 0.2 D with numbers X and Y of type number and a type 0.3 D with numbers X, Y and Z of type number. And then we have a type person with a name in an email. Then we create variables of each of these three types, so we can do some type comparison between them. Remember, the types in TypeScript are structural. This means that we can assign a 0.3 D to a 0.2 D without any errors because a 0.3 D does have all the members that are required by a 0.2 D, which is X and Y.
00:33
However, we cannot assign a 0.2 D to a 0.3 D because a 0.3 D requires a member Z, and this variable 0.2 simply does not have that. However, we can force this assignment to happen by using a type of session. Here we are saying that dear type script, I know you think this is a 0.2 D, but trust me, it is a 0.3 D and TypeScript being a nice companion happily agrees with you and trusts you completely. However, this single assertion is sometimes not enough. Let's look at an example.
01:06
We know that a 0.3 cannot be assigned to a person as there are no common members between them. The same is true that we cannot assign a person to a 0.3 because of this bidirectional incompatibility. If you try to assign a person to a 0.3, even with a single assertion, TypeScript will still complain. And if you hover over the error message, you can see that TypeScript is saying that this is probably a mistake. But if you still want to do something like this, then add an additional assertion to unknown. And if we do this process of first asserting to unknown
01:40
and then asserting to 0.3 D, indeed cript trust us and does not check us with any errors. Now, from our lesson on unknown, we can understand why this is working. Unknown is allowed at least one way. Compatibility with all types. That is a variable of all types can be assigned to a variable of type unknown. So anything can be assigned to unknown. For example, a person and an unknown can be asserted as anything, for example, a 0.3 D. So that is how our double assertion works.
02:12
And it goes without saying, use it with caution and avoid it as much as possible, but it might help you migrate some JavaScript code.